1、引言
JavaScript是一門(mén)基于原型繼承的語(yǔ)法,ES5中我們實(shí)現(xiàn)面向?qū)ο髽?gòu)造“父類”的寫(xiě)法一般通過(guò)構(gòu)造函數(shù)寫(xiě)入基本屬性、通過(guò)原型prototype寫(xiě)入基本的方法,下面是一個(gè)例子
demo
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的class可以看作一個(gè)語(yǔ)法糖,ES6中引入的新屬性class,通過(guò)class可以讓對(duì)象原型的寫(xiě)法更加清晰、更像面向?qū)ο缶幊痰恼Z(yǔ)法而已,上面的例子通過(guò)ES6的class改寫(xiě),
//定義一個(gè)Point類
class Point {
constructor(x,y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
- 嚴(yán)格模式
類和模塊的內(nèi)部,默認(rèn)就是嚴(yán)格模式,因而不需要使用use strict指定運(yùn)行模式。當(dāng)我們將代碼寫(xiě)在類和模塊之中,就只有嚴(yán)格模式可用
2、類的實(shí)例對(duì)象
當(dāng)我們生成類的實(shí)例對(duì)象的寫(xiě)法,與ES5完全一樣,即使用new命令,實(shí)例的屬性除顯式定義在本身(定義this對(duì)象),否則定義在原型上(定義在class上),下面寫(xiě)一個(gè)例子
//定義類
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)
//檢驗(yàn)實(shí)例的對(duì)象繼承的屬性在本身還是原型對(duì)象上
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
- 與ES5一樣,類的所有實(shí)例共享一個(gè)原型對(duì)象,demo測(cè)試如下
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__ === p2.__proto__ //true