function Modal(x, y) {
this.x = x;
this.y = y;
this.n = 100;
}
Modal.prototype.z = 10;
Modal.prototype.getX = function() {
console.log(this.x)
}
Modal.prototype.getY = function() {
console.log(this.y)
}
// 把Modal当做普通对象设置的私有属性方法,和实例没关系,直接用Modal访问
Modal.n = 200;
Modal.setNumber = function(n) {
this.n = n;
}
let m = new Modal(10, 20);
- ES6 中基于Class创建类和实例
class Modal {
// 构造函数
constructor(x, y) {
this.x = x;
this.y = y;
// this.n = 100;
}
n = 100; // ES7支持,等价于上句,不需要参数,固定值,可以在构造器外
// 原型上公共方法,只能下面这么写,直接 n = xxx是私有
// 公共属性无法直接设置,只能写外边
getX() {}
getY() {}
// 把其当做对象设置静态属性和方法
static n = 200;
static setNumber() {}
}
// 原型上的公共属性需要提到外边单独谢
Modal.prototype.z = 10;
let m = new Modal(10, 20);
// class创建的类不能作为普通函数执行