例如 :
class Parent {
foo() {
console.log("foo");
}
}
class Child extends Parent {
bar() {
console.log("bar");
}
}
在這里,運算式
Object.getPrototypeOf(Child) === Parent
將評估為真。
現在我了解了原型繼承的基礎知識以及類在 Javascript 中的作業原理,即每個函式都有一個屬性,在使用運算子呼叫函式時,該prototype屬性會復制到新創建的類實體的屬性中__proto__new
我也明白,Object.getPrototypeOf本質上回傳任何給定物件的屬性,通常我們通過將子類的屬性設定為父類的實體來__proto__模擬純javascript中的繼承,如下所示:prototype
function Parent(){}
Parent.prototype.foo = function(){
console.log("foo");
}
function Child(){}
// Inherit properties from Parent
Child.prototype = new Parent();
我的問題是:
Object.getPrototypeOf使用類作為引數呼叫時的結果代表什么?它如何與 TS/JS 中的類繼承相關聯?Object.getPrototypeOf用于檢查特定類是否在運行時擴展另一個類是否安全?
uj5u.com熱心網友回復:
關鍵字做了extends兩件事:
它將 SuperClass.prototype 物件設定為 SubClass.prototype 物件的原型。在您的情況下,
Child.prototype獲取Parent.prototype物件作為其原型。它還將超類的建構式設定為子類建構式的原型。在您的情況下,
Child建構式將Parent建構式作為其原型。
以上兩個陳述句本質上在代碼中意味著以下內容:
class Parent {}
class Child extends Parent {}
console.log(Object.getPrototypeOf(Child.prototype) === Parent.prototype);
console.log(Object.getPrototypeOf(Child) === Parent);
換句話說,extends關鍵字設定了兩個原型鏈:
Child.prototype ---> Parent.prototype ---> Object.prototype
Child ---> Parent ---> Function.prototype ---> Object.prototype
因此,Object.getPrototypeOf(Child)只需回傳Parent建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497502.html
