ES5创建构造函数
function Model(x, y) {
this.x = x;
this.y = y;
}
Model.prototype.z = 10;
Model.prototype.getX = function() {
console.log(this.x);
}
Model.n = 200;
Model.setNumber = function(n) {
this.n = n;
}
let m = new Model(10, 20);
m.getX();
Model.setNumber;
ES6创造构造函数
class Model {
constructor(x, y) {
this.x = x;
this.y = y;
}
z = 10;
getX = () => {};
getX() {
console.log(this.x);
}
getY() {
console.log(this.y);
}
static n = 200;
static setNumber = function(n) {
this.n = n;
}
}
let m = new Modal(10, 20);
console.dir(m);
console.dir(Modal);
- 基于class创建的构造函数,只能带new执行,也就是只能基于构造函数的方式去执行,不能当做普通函数执行「比ES5严谨很多」