let log = console.log;
function Animal(name)
{
this.name = name;
}
Animal.prototype.walk = function(){
log(`${this.name} walks`);
}
function Cat(name)
{
Animal.call(this,name);
this.lives = 9;
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.meow = function(){
log("Meow!");
}
let bambi = new Cat("Bambi");
log(bambi.constructor) // function Animal(name){ this.name = name; }
我已經使用 Cat 建構式創建了 'bambi' 物件,但是在檢查 bambi 的建構式時,它回傳了 Animal 建構式。我已經使用 Object.create() 將 Cat 的原型分配給 Animal 原型。為什么 bambi 物件的建構式是 Animal 而不是 Cat?
uj5u.com熱心網友回復:
查找“沒有類的javascript繼承”
在MDN 頁面上,它說:
- 在您之前添加的內容下方添加以下行:
Teacher.prototype = Object.create(Person.prototype);
復制到剪貼板 這里我們的朋友 create() 又來了。在這種情況下,我們使用它來創建一個新物件,并使其成為 Teacher.prototype 的值。新物件將 Person.prototype 作為其原型,因此將在需要時繼承 Person.prototype 上的所有可用方法。
- 在我們繼續之前,我們還需要做一件事。添加最后一行后,Teacher.prototype 的建構式屬性現在等于 Person(),因為我們只是將 Teacher.prototype 設定為參考一個從 Person.prototype 繼承其屬性的物件!嘗試保存您的代碼,在瀏覽器中加載頁面,然后在控制臺中輸入 Teacher.prototype.constructor 進行驗證。
- 這可能會成為一個問題,所以我們需要正確設定。您可以通過回傳源代碼并在底部添加以下行來實作:
Object.defineProperty(Teacher.prototype, 'constructor', {
value: Teacher,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true });
- 現在,如果您保存并重繪 ,輸入Teacher.prototype.constructor 應根據需要回傳Teacher(),而且我們現在從Person() 繼承!
因此,基于此,您的代碼需要添加這個小部分:
Object.defineProperty(Cat.prototype, 'constructor', {
value: Cat,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true });
請參閱下面的作業演示:
let log = console.log;
function Animal(name)
{
this.name = name;
}
Animal.prototype.walk = function(){
log(`${this.name} walks`);
}
function Cat(name)
{
Animal.call(this,name);
this.lives = 9;
}
Cat.prototype = Object.create(Animal.prototype);
Object.defineProperty(Cat.prototype, 'constructor', {
value: Cat,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true });
Cat.prototype.meow = function(){
log("Meow!");
}
let bambi = new Cat("Bambi");
log(bambi.constructor);
However, I would recommend just using ES6 classes instead of doing this manually
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337513.html
標籤:javascript 哎呀
上一篇:默認建構式引數錯誤-'Autoturism::Autoturism(char*,unsignedint)':無法將引數1從'constchar[6]'轉換為
