ES5中蝌焚,使用構(gòu)造函數(shù)是這樣的:
//定義類
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中近零,構(gòu)造函數(shù)
//定義類
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
上面中constructor
就是構(gòu)造方法堂油。
注意定義類的方法時(shí),前面不需要加上function
構(gòu)造函數(shù)的 prototype
屬性赌髓,在ES6中繼續(xù)存在。事實(shí)上催跪,類的所有方法都定義在prototype
屬性上面
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
在類的實(shí)例上面調(diào)用方法锁蠕,其實(shí)就是調(diào)用原型上的方法
class B {}
let b = new B();
b.constructor === B.prototype.constructor // true
由于類的方法都定義在prototype
對(duì)象上面,所以類的新方法可以添加在prototype對(duì)象上面叠荠。Object.assign方法可以很方便地一次向類添加多個(gè)方法匿沛。
class Point {
constructor(){
// ...
}
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});
類的實(shí)例對(duì)象
生成類的實(shí)例對(duì)象的寫(xiě)法,與ES5一樣榛鼎,也是使用new命令
class Point {
// ...
}
// 報(bào)錯(cuò)
var point = Point(2, 3);
// 正確
var point = new Point(2, 3);
與ES5一樣逃呼,實(shí)例的屬性除非顯式定義在其本身(即定義在this對(duì)象上,否則都是定義在原型上(即定義在class上)
//定義類
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Point(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
與ES5一樣者娱,在類的內(nèi)部可以使用get和set關(guān)鍵字抡笼,對(duì)耨個(gè)屬性設(shè)置存值函數(shù)和取值函數(shù),攔截該屬性的存取行為
class MyClass {
constructor() {
// ...
}
get prop() {
return 'getter';
}
set prop(value) {
console.log('setter: '+value);
}
}
let inst = new MyClass();
inst.prop = 123;
// setter: 123
inst.prop
// 'getter'