[英]Using the Prototype and Constructor Properties of JS in conjunction
據我了解,Prototype對象是其他對象從其繼承屬性和方法的對象,並且基本上它擁有一個構造器屬性,該構造器屬性引用或指向創建該對象的構造器函數。請考慮以下代碼:
function Animal()
{
this.name="no name";
}
function Cat()
{
Animal.Call(this); //Please Explain
this.mood="sleepy";
}
Cat.prototype=new Animal(); //Cat inheriting Animal?
Cat.prototype.constructor=Cat; //Please Explain
請清楚但詳細地解釋代碼行以及注釋和反射的概念,謝謝。
Animal.call(this)
的目的是什么
就像在其他編程語言中調用super()
一樣。 它在剛剛創建的新對象( this
)上調用父構造函數( Animal
)。 在有關.call
的MDN文檔中也對此進行了.call
。
在您的示例中, Animal
將"no name"
分配給this.name
。 因此,在調用Animal.call(this);
, this
將有一個name
屬性與上述值。
和
Cat.prototype.constructor=Cat;
默認情況下,每個原型的constructor
屬性都指向它所屬的函數。 但是由於您使用Cat.prototype=new Animal();
覆蓋了原型Cat.prototype=new Animal();
, constructor
屬性現在指向另一個函數。 在這種情況下,由於new Animal
返回的對象繼承自Animal.prototype
,因此Cat.prototype.constructor
將指向Animal
。 為了解決這個問題,我們再次分配了Cat
。
嚴格來講,這是沒有必要的,因為在任何內部函數中都沒有使用constructor
屬性。 但是,如果您的代碼依賴於此,則必須將其設置為正確的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.