ES5 的写法函数
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 的写法this
class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } }
在类的实例上面调用方法,其实就是调用原型上的方法。spa
class B {} let b = new B(); b.__proto__.constructor === B.prototype.constructor?console.log("true"):console.log("false") console.log(typeof b.__proto__.constructor) console.log(typeof B.prototype.constructor)
注:类的内部全部定义的方法,都是不可枚举的 prototype
constructor方法是类的默认方法,经过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,若是没有显式定义,一个空的constructor方法会被默认添加。
注意点3d
constructor方法默认返回实例对象(即this),彻底能够指定返回另一个对象。code
class Foo { constructor() { return Object.create(null); } } new Foo() instanceof Foo // false
类必须使用new调用,不然会报错。对象
class book{ constructor(){ this._year=2004; this.edition=1; } get year(){ return this._year; } set year(newVal){ if(newVal>2004){ this._year=newVal; this.edition+=newVal-2004; } } } let b=new book(); b.year = 2004; //2 console.log(b.edition);
class book{ constructor(){ this._year=2004; this.edition=1; } get year(){ return this._year; } set year(newVal){ if(newVal>2004){ this._year=newVal; this.edition+=newVal-2004; } } } let b=new book(); b.year = 2004; //2 console.log(b.edition);