2013-08-17 108 views
2

我已在最後一行以下參考父類的構造屬性在兒童構造在JavaScript

function mild_bird(){ 
    this.name = "catherine"; 
    this.origin = "st petersburg"; 
    this.location = "brighton beach"; 
} 

mild_bird.prototype.get_info = function(){ 
    return "poo" + ", " + "pee"; 
} 

function wild_bird(nickname){ 
    this.nickname = nickname; 
    //anyway to reference parameters in mild_bird constructor's? 
    this.name = mild_bird.prototype.name; 
    this.origin = mild_bird.prototype.origin; 
    this.location = mild_bird.prototype.location; 
} 

wild_bird.prototype = new mild_bird(); 
wild_bird.prototype.constructor = wild_bird; 

var the_wild_bird = new wild_bird("sandy"); 
alert(the_wild_bird.name); 

警報返回undefined。我希望它返回「凱瑟琳」。是否有可能在mild_bird的構造函數中將屬性傳遞給wild_bird的構造函數?

回答

1

您必須在子構造函數中調用父類的構造函數。使用.call(this)可確保將上下文設置爲由childrens構造函數創建的對象。

function wild_bird(nickname){ 
    mild_bird.call(this); 
    this.nickname = nickname; 
}