一萬字ES6的class類,再學不懂,請來找我(語法篇)
大廠技術??高級前端??Node進階
點擊上方?程序員成長指北,關注公眾號
回復1,加入高級Node交流群
JavaScript 語言中,生成實例對象的傳統(tǒng)方法是通過構造函數(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);
上面這種寫法跟傳統(tǒng)的面向對象語言(比如 C++ 和 Java)差異很大,很容易讓新學習這門語言的程序員感到困惑。
ES6 提供了更接近傳統(tǒng)語言的寫法,引入了 Class(類)這個概念,作為對象的模板。通過class關鍵字,可以定義類。
基本上,ES6 的class可以看作只是一個語法糖,它的絕大部分功能,ES5 都可以做到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。上面的代碼用 ES6 的class改寫,就是下面這樣。
class?Point?{
??constructor(x,?y)?{
????this.x?=?x;
????this.y?=?y;
??}
??toString()?{
????return?'('?+?this.x?+?',?'?+?this.y?+?')';
??}
}
上面代碼定義了一個“類”,可以看到里面有一個constructor()方法,這就是構造方法,而this關鍵字則代表實例對象。這種新的 Class 寫法,本質上與本章開頭的 ES5 的構造函數(shù)Point是一致的。
Point類除了構造方法,還定義了一個toString()方法。注意,定義toString()方法的時候,前面不需要加上function這個關鍵字,直接把函數(shù)定義放進去了就可以了。另外,方法與方法之間不需要逗號分隔,加了會報錯。
ES6 的類,完全可以看作構造函數(shù)的另一種寫法。
class?Point?{
??//?...
}
typeof?Point?//?"function"
Point?===?Point.prototype.constructor?//?true
上面代碼表明,類的數(shù)據(jù)類型就是函數(shù),類本身就指向構造函數(shù)。
使用的時候,也是直接對類使用new命令,跟構造函數(shù)的用法完全一致。
class?Bar?{
??doStuff()?{
????console.log('stuff');
??}
}
const?b?=?new?Bar();
b.doStuff()?//?"stuff"
構造函數(shù)的prototype屬性,在 ES6 的“類”上面繼續(xù)存在。事實上,類的所有方法都定義在類的prototype屬性上面。
class?Point?{
??constructor()?{
????//?...
??}
??toString()?{
????//?...
??}
??toValue()?{
????//?...
??}
}
//?等同于
Point.prototype?=?{
??constructor()?{},
??toString()?{},
??toValue()?{},
};
上面代碼中,constructor()、toString()、toValue()這三個方法,其實都是定義在Point.prototype上面。
因此,在類的實例上面調用方法,其實就是調用原型上的方法。
class?B?{}
const?b?=?new?B();
b.constructor?===?B.prototype.constructor?//?true
上面代碼中,b是B類的實例,它的constructor()方法就是B類原型的constructor()方法。
由于類的方法都定義在prototype對象上面,所以類的新方法可以添加在prototype對象上面。Object.assign()方法可以很方便地一次向類添加多個方法。
class?Point?{
??constructor(){
????//?...
??}
}
Object.assign(Point.prototype,?{
??toString(){},
??toValue(){}
});
prototype對象的constructor()屬性,直接指向“類”的本身,這與 ES5 的行為是一致的。
Point.prototype.constructor?===?Point?//?true
另外,類的內部所有定義的方法,都是不可枚舉的(non-enumerable)。
class?Point?{
??constructor(x,?y)?{
????//?...
??}
??toString()?{
????//?...
??}
}
Object.keys(Point.prototype)
//?[]
Object.getOwnPropertyNames(Point.prototype)
//?["constructor","toString"]
上面代碼中,toString()方法是Point類內部定義的方法,它是不可枚舉的。這一點與 ES5 的行為不一致。
var?Point?=?function?(x,?y)?{
??//?...
};
Point.prototype.toString?=?function?()?{
??//?...
};
Object.keys(Point.prototype)
//?["toString"]
Object.getOwnPropertyNames(Point.prototype)
//?["constructor","toString"]
上面代碼采用 ES5 的寫法,toString()方法就是可枚舉的。
constructor 方法
constructor()方法是類的默認方法,通過new命令生成對象實例時,自動調用該方法。一個類必須有constructor()方法,如果沒有顯式定義,一個空的constructor()方法會被默認添加。
class?Point?{
}
//?等同于
class?Point?{
??constructor()?{}
}
上面代碼中,定義了一個空的類Point,JavaScript 引擎會自動為它添加一個空的constructor()方法。
constructor()方法默認返回實例對象(即this),完全可以指定返回另外一個對象。
class?Foo?{
??constructor()?{
????return?Object.create(null);
??}
}
new?Foo()?instanceof?Foo
//?false
上面代碼中,constructor()函數(shù)返回一個全新的對象,結果導致實例對象不是Foo類的實例。
類必須使用new調用,否則會報錯。這是它跟普通構造函數(shù)的一個主要區(qū)別,后者不用new也可以執(zhí)行。
class?Foo?{
??constructor()?{
????return?Object.create(null);
??}
}
Foo()
//?TypeError:?Class?constructor?Foo?cannot?be?invoked?without?'new'
類的實例
生成類的實例的寫法,與 ES5 完全一樣,也是使用new命令。前面說過,如果忘記加上new,像函數(shù)那樣調用Class,將會報錯。
class?Point?{
??//?...
}
//?報錯
var?point?=?Point(2,?3);
//?正確
var?point?=?new?Point(2,?3);
與 ES5 一樣,實例的屬性除非顯式定義在其本身(即定義在this對象上),否則都是定義在原型上(即定義在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
上面代碼中,x和y都是實例對象point自身的屬性(因為定義在this對象上),所以hasOwnProperty()方法返回true,而toString()是原型對象的屬性(因為定義在Point類上),所以hasOwnProperty()方法返回false。這些都與 ES5 的行為保持一致。
與 ES5 一樣,類的所有實例共享一個原型對象。
var?p1?=?new?Point(2,3);
var?p2?=?new?Point(3,2);
p1.__proto__?===?p2.__proto__
//true
上面代碼中,p1和p2都是Point的實例,它們的原型都是Point.prototype,所以__proto__屬性是相等的。
這也意味著,可以通過實例的__proto__屬性為“類”添加方法。
“”
__proto__并不是語言本身的特性,這是各大廠商具體實現(xiàn)時添加的私有屬性,雖然目前很多現(xiàn)代瀏覽器的 JS 引擎中都提供了這個私有屬性,但依舊不建議在生產中使用該屬性,避免對環(huán)境產生依賴。生產環(huán)境中,我們可以使用Object.getPrototypeOf方法來獲取實例對象的原型,然后再來為原型添加方法/屬性。
var?p1?=?new?Point(2,3);
var?p2?=?new?Point(3,2);
p1.__proto__.printName?=?function?()?{?return?'Oops'?};
p1.printName()?//?"Oops"
p2.printName()?//?"Oops"
var?p3?=?new?Point(4,2);
p3.printName()?//?"Oops"
上面代碼在p1的原型上添加了一個printName()方法,由于p1的原型就是p2的原型,因此p2也可以調用這個方法。而且,此后新建的實例p3也可以調用這個方法。這意味著,使用實例的__proto__屬性改寫原型,必須相當謹慎,不推薦使用,因為這會改變“類”的原始定義,影響到所有實例。
取值函數(shù)(getter)和存值函數(shù)(setter)
與 ES5 一樣,在“類”的內部可以使用get和set關鍵字,對某個屬性設置存值函數(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'
上面代碼中,prop屬性有對應的存值函數(shù)和取值函數(shù),因此賦值和讀取行為都被自定義了。
存值函數(shù)和取值函數(shù)是設置在屬性的 Descriptor 對象上的。
class?CustomHTMLElement?{
??constructor(element)?{
????this.element?=?element;
??}
??get?html()?{
????return?this.element.innerHTML;
??}
??set?html(value)?{
????this.element.innerHTML?=?value;
??}
}
var?descriptor?=?Object.getOwnPropertyDescriptor(
??CustomHTMLElement.prototype,?"html"
);
"get"?in?descriptor??//?true
"set"?in?descriptor??//?true
上面代碼中,存值函數(shù)和取值函數(shù)是定義在html屬性的描述對象上面,這與 ES5 完全一致。
屬性表達式
類的屬性名,可以采用表達式。
let?methodName?=?'getArea';
class?Square?{
??constructor(length)?{
????//?...
??}
??[methodName]()?{
????//?...
??}
}
上面代碼中,Square類的方法名getArea,是從表達式得到的。
Class 表達式
與函數(shù)一樣,類也可以使用表達式的形式定義。
const?MyClass?=?class?Me?{
??getClassName()?{
????return?Me.name;
??}
};
上面代碼使用表達式定義了一個類。需要注意的是,這個類的名字是Me,但是Me只在 Class 的內部可用,指代當前類。在 Class 外部,這個類只能用MyClass引用。
let?inst?=?new?MyClass();
inst.getClassName()?//?Me
Me.name?//?ReferenceError:?Me?is?not?defined
上面代碼表示,Me只在 Class 內部有定義。
如果類的內部沒用到的話,可以省略Me,也就是可以寫成下面的形式。
const?MyClass?=?class?{?/*?...?*/?};
采用 Class 表達式,可以寫出立即執(zhí)行的 Class。
let?person?=?new?class?{
??constructor(name)?{
????this.name?=?name;
??}
??sayName()?{
????console.log(this.name);
??}
}('張三');
person.sayName();?//?"張三"
上面代碼中,person是一個立即執(zhí)行的類的實例。
注意點
(1)嚴格模式
類和模塊的內部,默認就是嚴格模式,所以不需要使用use strict指定運行模式。只要你的代碼寫在類或模塊之中,就只有嚴格模式可用??紤]到未來所有的代碼,其實都是運行在模塊之中,所以 ES6 實際上把整個語言升級到了嚴格模式。
(2)不存在提升
類不存在變量提升(hoist),這一點與 ES5 完全不同。
new?Foo();?//?ReferenceError
class?Foo?{}
上面代碼中,Foo類使用在前,定義在后,這樣會報錯,因為 ES6 不會把類的聲明提升到代碼頭部。這種規(guī)定的原因與下文要提到的繼承有關,必須保證子類在父類之后定義。
{
??let?Foo?=?class?{};
??class?Bar?extends?Foo?{
??}
}
上面的代碼不會報錯,因為Bar繼承Foo的時候,Foo已經(jīng)有定義了。但是,如果存在class的提升,上面代碼就會報錯,因為class會被提升到代碼頭部,而let命令是不提升的,所以導致Bar繼承Foo的時候,Foo還沒有定義。
(3)name 屬性
由于本質上,ES6 的類只是 ES5 的構造函數(shù)的一層包裝,所以函數(shù)的許多特性都被Class繼承,包括name屬性。
class?Point?{}
Point.name?//?"Point"
name屬性總是返回緊跟在class關鍵字后面的類名。
(4)Generator 方法
如果某個方法之前加上星號(*),就表示該方法是一個 Generator 函數(shù)。
class?Foo?{
??constructor(...args)?{
????this.args?=?args;
??}
??*?[Symbol.iterator]()?{
????for?(let?arg?of?this.args)?{
??????yield?arg;
????}
??}
}
for?(let?x?of?new?Foo('hello',?'world'))?{
??console.log(x);
}
//?hello
//?world
上面代碼中,Foo類的Symbol.iterator方法前有一個星號,表示該方法是一個 Generator 函數(shù)。Symbol.iterator方法返回一個Foo類的默認遍歷器,for...of循環(huán)會自動調用這個遍歷器。
(5)this 的指向
類的方法內部如果含有this,它默認指向類的實例。但是,必須非常小心,一旦單獨使用該方法,很可能報錯。
class?Logger?{
??printName(name?=?'there')?{
????this.print(`Hello?${name}`);
??}
??print(text)?{
????console.log(text);
??}
}
const?logger?=?new?Logger();
const?{?printName?}?=?logger;
printName();?//?TypeError:?Cannot?read?property?'print'?of?undefined
上面代碼中,printName方法中的this,默認指向Logger類的實例。但是,如果將這個方法提取出來單獨使用,this會指向該方法運行時所在的環(huán)境(由于 class 內部是嚴格模式,所以 this 實際指向的是undefined),從而導致找不到print方法而報錯。
一個比較簡單的解決方法是,在構造方法中綁定this,這樣就不會找不到print方法了。
class?Logger?{
??constructor()?{
????this.printName?=?this.printName.bind(this);
??}
??//?...
}
另一種解決方法是使用箭頭函數(shù)。
class?Obj?{
??constructor()?{
????this.getThis?=?()?=>?this;
??}
}
const?myObj?=?new?Obj();
myObj.getThis()?===?myObj?//?true
箭頭函數(shù)內部的this總是指向定義時所在的對象。上面代碼中,箭頭函數(shù)位于構造函數(shù)內部,它的定義生效的時候,是在構造函數(shù)執(zhí)行的時候。這時,箭頭函數(shù)所在的運行環(huán)境,肯定是實例對象,所以this會總是指向實例對象。
還有一種解決方法是使用Proxy,獲取方法的時候,自動綁定this。
function?selfish?(target)?{
??const?cache?=?new?WeakMap();
??const?handler?=?{
????get?(target,?key)?{
??????const?value?=?Reflect.get(target,?key);
??????if?(typeof?value?!==?'function')?{
????????return?value;
??????}
??????if?(!cache.has(value))?{
????????cache.set(value,?value.bind(target));
??????}
??????return?cache.get(value);
????}
??};
??const?proxy?=?new?Proxy(target,?handler);
??return?proxy;
}
const?logger?=?selfish(new?Logger());
靜態(tài)方法
類相當于實例的原型,所有在類中定義的方法,都會被實例繼承。如果在一個方法前,加上static關鍵字,就表示該方法不會被實例繼承,而是直接通過類來調用,這就稱為“靜態(tài)方法”。
class?Foo?{
??static?classMethod()?{
????return?'hello';
??}
}
Foo.classMethod()?//?'hello'
var?foo?=?new?Foo();
foo.classMethod()
//?TypeError:?foo.classMethod?is?not?a?function
上面代碼中,Foo類的classMethod方法前有static關鍵字,表明該方法是一個靜態(tài)方法,可以直接在Foo類上調用(Foo.classMethod()),而不是在Foo類的實例上調用。如果在實例上調用靜態(tài)方法,會拋出一個錯誤,表示不存在該方法。
注意,如果靜態(tài)方法包含this關鍵字,這個this指的是類,而不是實例。
class?Foo?{
??static?bar()?{
????this.baz();
??}
??static?baz()?{
????console.log('hello');
??}
??baz()?{
????console.log('world');
??}
}
Foo.bar()?//?hello
上面代碼中,靜態(tài)方法bar調用了this.baz,這里的this指的是Foo類,而不是Foo的實例,等同于調用Foo.baz。另外,從這個例子還可以看出,靜態(tài)方法可以與非靜態(tài)方法重名。
父類的靜態(tài)方法,可以被子類繼承。
class?Foo?{
??static?classMethod()?{
????return?'hello';
??}
}
class?Bar?extends?Foo?{
}
Bar.classMethod()?//?'hello'
上面代碼中,父類Foo有一個靜態(tài)方法,子類Bar可以調用這個方法。
靜態(tài)方法也是可以從super對象上調用的。
class?Foo?{
??static?classMethod()?{
????return?'hello';
??}
}
class?Bar?extends?Foo?{
??static?classMethod()?{
????return?super.classMethod()?+?',?too';
??}
}
Bar.classMethod()?//?"hello,?too"
實例屬性的新寫法
實例屬性除了定義在constructor()方法里面的this上面,也可以定義在類的最頂層。
class?IncreasingCounter?{
??constructor()?{
????this._count?=?0;
??}
??get?value()?{
????console.log('Getting?the?current?value!');
????return?this._count;
??}
??increment()?{
????this._count++;
??}
}
上面代碼中,實例屬性this._count定義在constructor()方法里面。另一種寫法是,這個屬性也可以定義在類的最頂層,其他都不變。
class?IncreasingCounter?{
??_count?=?0;
??get?value()?{
????console.log('Getting?the?current?value!');
????return?this._count;
??}
??increment()?{
????this._count++;
??}
}
上面代碼中,實例屬性_count與取值函數(shù)value()和increment()方法,處于同一個層級。這時,不需要在實例屬性前面加上this。
這種新寫法的好處是,所有實例對象自身的屬性都定義在類的頭部,看上去比較整齊,一眼就能看出這個類有哪些實例屬性。
class?foo?{
??bar?=?'hello';
??baz?=?'world';
??constructor()?{
????//?...
??}
}
上面的代碼,一眼就能看出,foo類有兩個實例屬性,一目了然。另外,寫起來也比較簡潔。
靜態(tài)屬性
靜態(tài)屬性指的是 Class 本身的屬性,即Class.propName,而不是定義在實例對象(this)上的屬性。
class?Foo?{
}
Foo.prop?=?1;
Foo.prop?//?1
上面的寫法為Foo類定義了一個靜態(tài)屬性prop。
目前,只有這種寫法可行,因為 ES6 明確規(guī)定,Class 內部只有靜態(tài)方法,沒有靜態(tài)屬性?,F(xiàn)在有一個提案[1]提供了類的靜態(tài)屬性,寫法是在實例屬性的前面,加上static關鍵字。
class?MyClass?{
??static?myStaticProp?=?42;
??constructor()?{
????console.log(MyClass.myStaticProp);?//?42
??}
}
這個新寫法大大方便了靜態(tài)屬性的表達。
//?老寫法
class?Foo?{
??//?...
}
Foo.prop?=?1;
//?新寫法
class?Foo?{
??static?prop?=?1;
}
上面代碼中,老寫法的靜態(tài)屬性定義在類的外部。整個類生成以后,再生成靜態(tài)屬性。這樣讓人很容易忽略這個靜態(tài)屬性,也不符合相關代碼應該放在一起的代碼組織原則。另外,新寫法是顯式聲明(declarative),而不是賦值處理,語義更好。
私有方法和私有屬性
現(xiàn)有的解決方案
私有方法和私有屬性,是只能在類的內部訪問的方法和屬性,外部不能訪問。這是常見需求,有利于代碼的封裝,但 ES6 不提供,只能通過變通方法模擬實現(xiàn)。
一種做法是在命名上加以區(qū)別。
class?Widget?{
??//?公有方法
??foo?(baz)?{
????this._bar(baz);
??}
??//?私有方法
??_bar(baz)?{
????return?this.snaf?=?baz;
??}
??//?...
}
上面代碼中,_bar()方法前面的下劃線,表示這是一個只限于內部使用的私有方法。但是,這種命名是不保險的,在類的外部,還是可以調用到這個方法。
另一種方法就是索性將私有方法移出類,因為類內部的所有方法都是對外可見的。
class?Widget?{
??foo?(baz)?{
????bar.call(this,?baz);
??}
??//?...
}
function?bar(baz)?{
??return?this.snaf?=?baz;
}
上面代碼中,foo是公開方法,內部調用了bar.call(this, baz)。這使得bar()實際上成為了當前類的私有方法。
還有一種方法是利用Symbol值的唯一性,將私有方法的名字命名為一個Symbol值。
const?bar?=?Symbol('bar');
const?snaf?=?Symbol('snaf');
export?default?class?myClass{
??//?公有方法
??foo(baz)?{
????this[bar](baz);
??}
??//?私有方法
??[bar](baz)?{
????return?this[snaf]?=?baz;
??}
??//?...
};
上面代碼中,bar和snaf都是Symbol值,一般情況下無法獲取到它們,因此達到了私有方法和私有屬性的效果。但是也不是絕對不行,Reflect.ownKeys()依然可以拿到它們。
const?inst?=?new?myClass();
Reflect.ownKeys(myClass.prototype)
//?[?'constructor',?'foo',?Symbol(bar)?]
上面代碼中,Symbol 值的屬性名依然可以從類的外部拿到。
私有屬性的提案
目前,有一個提案[2],為class加了私有屬性。方法是在屬性名之前,使用#表示。
class?IncreasingCounter?{
??#count?=?0;
??get?value()?{
????console.log('Getting?the?current?value!');
????return?this.#count;
??}
??increment()?{
????this.#count++;
??}
}
上面代碼中,#count就是私有屬性,只能在類的內部使用(this.#count)。如果在類的外部使用,就會報錯。
const?counter?=?new?IncreasingCounter();
counter.#count?//?報錯
counter.#count?=?42?//?報錯
上面代碼在類的外部,讀取私有屬性,就會報錯。
下面是另一個例子。
class?Point?{
??#x;
??constructor(x?=?0)?{
????this.#x?=?+x;
??}
??get?x()?{
????return?this.#x;
??}
??set?x(value)?{
????this.#x?=?+value;
??}
}
上面代碼中,#x就是私有屬性,在Point類之外是讀取不到這個屬性的。由于井號#是屬性名的一部分,使用時必須帶有#一起使用,所以#x和x是兩個不同的屬性。
之所以要引入一個新的前綴#表示私有屬性,而沒有采用private關鍵字,是因為 JavaScript 是一門動態(tài)語言,沒有類型聲明,使用獨立的符號似乎是唯一的比較方便可靠的方法,能夠準確地區(qū)分一種屬性是否為私有屬性。另外,Ruby 語言使用@表示私有屬性,ES6 沒有用這個符號而使用#,是因為@已經(jīng)被留給了 Decorator。
這種寫法不僅可以寫私有屬性,還可以用來寫私有方法。
class?Foo?{
??#a;
??#b;
??constructor(a,?b)?{
????this.#a?=?a;
????this.#b?=?b;
??}
??#sum()?{
????return?this.#a?+?this.#b;
??}
??printSum()?{
????console.log(this.#sum());
??}
}
上面代碼中,#sum()就是一個私有方法。
另外,私有屬性也可以設置 getter 和 setter 方法。
class?Counter?{
??#xValue?=?0;
??constructor()?{
????super();
????//?...
??}
??get?#x()?{?return?#xValue;?}
??set?#x(value)?{
????this.#xValue?=?value;
??}
}
上面代碼中,#x是一個私有屬性,它的讀寫都通過get #x()和set #x()來完成。
私有屬性不限于從this引用,只要是在類的內部,實例也可以引用私有屬性。
class?Foo?{
??#privateValue?=?42;
??static?getPrivateValue(foo)?{
????return?foo.#privateValue;
??}
}
Foo.getPrivateValue(new?Foo());?//?42
上面代碼允許從實例foo上面引用私有屬性。
私有屬性和私有方法前面,也可以加上static關鍵字,表示這是一個靜態(tài)的私有屬性或私有方法。
class?FakeMath?{
??static?PI?=?22?/?7;
??static?#totallyRandomNumber?=?4;
??static?#computeRandomNumber()?{
????return?FakeMath.#totallyRandomNumber;
??}
??static?random()?{
????console.log('I?heard?you?like?random?numbers…')
????return?FakeMath.#computeRandomNumber();
??}
}
FakeMath.PI?//?3.142857142857143
FakeMath.random()
//?I?heard?you?like?random?numbers…
//?4
FakeMath.#totallyRandomNumber?//?報錯
FakeMath.#computeRandomNumber()?//?報錯
上面代碼中,#totallyRandomNumber是私有屬性,#computeRandomNumber()是私有方法,只能在FakeMath這個類的內部調用,外部調用就會報錯。
in 運算符
try...catch結構可以用來判斷是否存在某個私有屬性。
class?A?{
??use(obj)?{
????try?{
??????obj.#foo;
????}?catch?{
??????//?私有屬性?#foo?不存在
????}
??}
}
const?a?=?new?A();
a.use(a);?//?報錯
上面示例中,類A并不存在私有屬性#foo,所以try...catch報錯了。
這樣的寫法很麻煩,可讀性很差,V8 引擎改進了in運算符,使它也可以用來判斷私有屬性。
class?A?{
??use(obj)?{
????if?(#foo?in?obj)?{
??????//?私有屬性?#foo?存在
????}?else?{
??????//?私有屬性?#foo?不存在
????}
??}
}
上面示例中,in運算符判斷當前類A的實例,是否有私有屬性#foo,如果有返回true,否則返回false。
in也可以跟this一起配合使用。
class?A?{
??#foo?=?0;
??m()?{
????console.log(#foo?in?this);?//?true
????console.log(#bar?in?this);?//?false
??}
}
注意,判斷私有屬性時,in只能用在定義該私有屬性的類的內部。
class?A?{
??#foo?=?0;
??static?test(obj)?{
????console.log(#foo?in?obj);
??}
}
A.test(new?A())?//?true
A.test({})?//?false
class?B?{
??#foo?=?0;
}
A.test(new?B())?//?false
上面示例中,類A的私有屬性#foo,只能在類A內部使用in運算符判斷,而且只對A的實例返回true,對于其他對象都返回false。
子類從父類繼承的私有屬性,也可以使用in運算符來判斷。
class?A?{
??#foo?=?0;
??static?test(obj)?{
????console.log(#foo?in?obj);
??}
}
class?SubA?extends?A?{};
A.test(new?SubA())?//?true
上面示例中,SubA從父類繼承了私有屬性#foo,in運算符也有效。
注意,in運算符對于Object.create()、Object.setPrototypeOf形成的繼承,是無效的,因為這種繼承不會傳遞私有屬性。
class?A?{
??#foo?=?0;
??static?test(obj)?{
????console.log(#foo?in?obj);
??}
}
const?a?=?new?A();
const?o1?=?Object.create(a);
A.test(o1)?//?false
A.test(o1.__proto__)?//?true
const?o2?=?{};
Object.setPrototypeOf(o2,?A);
A.test(o2)?//?false
A.test(o2.__proto__)?//?true
上面示例中,對于修改原型鏈形成的繼承,子類都取不到父類的私有屬性,所以in運算符無效。
new.target 屬性
new是從構造函數(shù)生成實例對象的命令。ES6 為new命令引入了一個new.target屬性,該屬性一般用在構造函數(shù)之中,返回new命令作用于的那個構造函數(shù)。如果構造函數(shù)不是通過new命令或Reflect.construct()調用的,new.target會返回undefined,因此這個屬性可以用來確定構造函數(shù)是怎么調用的。
function?Person(name)?{
??if?(new.target?!==?undefined)?{
????this.name?=?name;
??}?else?{
????throw?new?Error('必須使用?new?命令生成實例');
??}
}
//?另一種寫法
function?Person(name)?{
??if?(new.target?===?Person)?{
????this.name?=?name;
??}?else?{
????throw?new?Error('必須使用?new?命令生成實例');
??}
}
var?person?=?new?Person('張三');?//?正確
var?notAPerson?=?Person.call(person,?'張三');??//?報錯
上面代碼確保構造函數(shù)只能通過new命令調用。
Class 內部調用new.target,返回當前 Class。
class?Rectangle?{
??constructor(length,?width)?{
????console.log(new.target?===?Rectangle);
????this.length?=?length;
????this.width?=?width;
??}
}
var?obj?=?new?Rectangle(3,?4);?//?輸出?true
需要注意的是,子類繼承父類時,new.target會返回子類。
class?Rectangle?{
??constructor(length,?width)?{
????console.log(new.target?===?Rectangle);
????//?...
??}
}
class?Square?extends?Rectangle?{
??constructor(length,?width)?{
????super(length,?width);
??}
}
var?obj?=?new?Square(3);?//?輸出?false
上面代碼中,new.target會返回子類。
利用這個特點,可以寫出不能獨立使用、必須繼承后才能使用的類。
class?Shape?{
??constructor()?{
????if?(new.target?===?Shape)?{
??????throw?new?Error('本類不能實例化');
????}
??}
}
class?Rectangle?extends?Shape?{
??constructor(length,?width)?{
????super();
????//?...
??}
}
var?x?=?new?Shape();??//?報錯
var?y?=?new?Rectangle(3,?4);??//?正確
上面代碼中,Shape類不能被實例化,只能用于繼承。
注意,在函數(shù)外部,使用new.target會報錯。
原文地址
https://juejin.cn/post/7000891889465425957? ? ? ? ? ? ? ? ? ? ??
我組建了一個氛圍特別好的 Node.js 社群,里面有很多 Node.js小伙伴,如果你對Node.js學習感興趣的話(后續(xù)有計劃也可以),我們可以一起進行Node.js相關的交流、學習、共建。下方加 考拉 好友回復「Node」即可。
???“分享、點贊、在看” 支持一波??
