js类的写法

js类的写法

ES5标准:

写法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//定义
var AsyncMessage = function (orgid, orgddkey, msgtype){
var _this = this;
_this.orgid = orgid;
_this.orgddkey = orgddkey;
_this.msgtype = msgtype || 'oa';
_this.access_token = '';
return {
getDingAccessToken : function (){
console.log('我是getDingAccessToken');
},
sendAsyncMsg : function (){
console.log('我是sendAsyncMsg');
},
sendDingMsg : function () {
console.log('我是sendDingMsg');
}
}
}
//调用
var mainMessage = new AsyncMessage('abcde','C7wDa_u3qa','ding');
mainMessage.sendDingMsg();

写法二:

1
2
3
4
5
6
7
8
9
10
11
//通过构造函数
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);

ES6标准

引入了 Class(类)这个概念

类和模块的内部,默认就是严格模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//定义类
class Point {
/*构造函数*/
constructor(x, y) {
this.x = x;
this.y = y;
}
//方法与方法之间不需要逗号
toString() {
//......
}
toValue() {
//.....
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};