簡體   English   中英

JS中的構造函數和原型屬性

[英]Constructors and prototype properties in JS

我正在弄清楚JS中的原型,而我無法弄清為什么這不起作用:

var Mammal = {
    legs: 4
}

function Dog(color, soundItMakes) {
    this.prototype = Mammal;
    this.color = color;
    this.soundItMakes = soundItMakes;
    this.woof = function() { return this.soundItMakes; }
}

aDog = new Dog("brown", "beep beep!");
document.write(Mammal.legs + "<br>");
document.write(aDog.color + "<br>" + aDog.woof() + "<br>" + aDog.legs);

第一個document.write()返回預期的4,但是第二個返回的aDog.legs未定義。 任何建議都會有很大幫助。

現在, prototypeDog實例對象的自身屬性。 因此,如果您願意,可以像aDog.prototype.legs一樣訪問它。 但是,這與設置Dog 構造函數prototype不同

您的代碼應為:

var Mammal = {
    legs: 4
}

function Dog(color, soundItMakes) {
    this.color = color;
    this.soundItMakes = soundItMakes;
    this.woof = function() { return this.soundItMakes; }
}

Dog.prototype = Mammal;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM