2015-02-07 71 views
0

我不能理解線4
如果我寫這樣derive.constructor.prototype
會發生錯誤。JavaScript的繼承constructor.prototype

還有,什麼是base.apply(derive, baseArgs);
我以爲我可以像base(baseArg)那樣做我無法做到這一點。

function initializeBase(derive, base, baseArgs) { 
    base.apply(derive, baseArgs); 
    for(var prop in base.prototype) { 
    var proto = derive.constructor.prototype; 
    if(!proto[prop]) { 
     proto[prop] = base.prototype[prop]; 
    } 
    } 
} 

var Member = function(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
}; 

Member.prototype.getName = function() { 
    return this.firstName + ' ' + this.lastName; 
}; 

var SpecialMember = function(firstName, lastName, role) { 
    initializeBase(this, Member, [firstName, lastName]); 

    this.role = role; 
}; 

SpecialMember.prototype.isAdministrator = function() { 
    return (this.role == 'Administrator'); 
}; 

var mem = new SpecialMember('Kotaro', 'Hayafune', 'Administrator'); 
document.writeln('Name: ' + mem.getName() + '<br>'); 
document.writeln('Administrator: ' + mem.isAdministrator()); 
+0

你從哪裏獲得'initializeBase'函數? – Bergi 2015-02-07 10:21:20

回答

0

不知道你的變量,這裏包含但通常如果你想原型你可以這樣寫:

var proto = derive.prototype; 

,如果你想要的構造函數,你會寫:

var constr = derive.prototype.constructor;