1普通创建类的方法
function Modal(x, y) {// 给实例设置的私有属性方法this.x = x;this.y = y;}// 在类的原型上扩展的公共属性方法「供实例调用的」Modal.prototype.z = 10;Modal.prototype.getX = function () {console.log(this.x);}Modal.prototype.getY = function () {console.log(this.y);}// 把它当做普通对象,设置的静态私有属性方法Modal.n = 200;Modal.setNumber = function (n) {this.n = n;};
2.用ES6语法
class创建的构造函数,不能Fn()执行,只能new执行 不能给原型增加属性,只能增加方法
class Model {// 构造函数体:给实例设置的私有属性和方法constructor(x, y) {this.x = x;this.y = y;}// z = 10; //直接这样写,是给实例设置的私有属性// 向类的prototype上扩展方法{特点:这里只能给prototype设置公共的方法,属性设置不了,如果想设置,只能在外面自己加}getX() {console.log(this.x);}getY() {console.log(this.y);}// 当做普通对象,设置的静态私有属性方法static n = 20;static setNumber(n) {this.n = n;}}Model.prototype.z = 10;let m = new Model(10, 20);//Model() //Uncaught TypeError: Class constructor Model cannot be invoked without 'new'
例2:
// function Fn(num) {// this.x = this.y = num;// }// Fn.prototype.x = 20;// Fn.prototype.sum = function () {// console.log(this.x + this.y);// };// Fn.a = 1;class Fn {constructor(num) {this.x = this.y = num;}// x=20;不能直接在class里面增加原型上的属性,实例私有的a=1;//实例私有的static b=2;//写在函数堆里Fn的私有属性sum() {// Fn原型上的console.log(this.x + this.y);}}Fn.prototype.a=1;//原型上的属性a// class创建的构造函数不能Fn(),只能new Fn。console.dir(new Fn);


