2016-10-30 57 views
0
var A = function() { 
    this.p1 = 2; 
}; 
A.prototype.f1 = function() { 
    return 7; 
}; 
var B = function() { 
    inherit(A, B); 
}; 


function inherit(Child, Parent) { 
    Child.prototype = Object.create(Parent.prototype); 
    Child.prototype.constructor = Child; 
} 

var b = new B(); 
console.log(b.p1); // get undefined here 

我是JS新手,抱歉轉儲問題。我想從A繼承B。我究竟做錯了什麼?JavaScript:在ECMAScript5中的繼承

回答

1

我在做什麼錯?

兩件事情:

  1. 你打電話inheritB。你應該在外面去做。

  2. 裏面B,你應該打電話A,例如,

    A.call(this/*, other, args, here, if, needed*/); 
    

    A.apply(this, arguments); 
    

    通過對所有的B經由自動arguments僞陣列在運行時接收到的參數。

像這樣:

var A = function() { 
 
    this.p1 = 2; 
 
}; 
 
A.prototype.f1 = function() { 
 
    return 7; 
 
}; 
 
var B = function() { 
 
    A.call(this);  // <==== Added 
 
}; 
 
inherit(A, B);   // <==== Moved 
 

 
function inherit(Child, Parent) { 
 
    Child.prototype = Object.create(Parent.prototype); 
 
    Child.prototype.constructor = Child; 
 
} 
 

 
var b = new B(); 
 
console.log(b.p1); // get 2 here now

+0

感謝您的回答! T.J. Crowder,請你簡單解釋一下在調用'A.call(this)時會發生什麼;' –

+0

@Rudziankoŭ:當你執行'A.call(x,y,z)'時,它會調用函數'A'在'A'的代碼中'this'是'x',然後傳遞'y'和'z'作爲參數。它基本上做了'foo.bar(y,z)'做的事情(使'bar'內的'this'成爲'foo'),而不必涉及對象屬性表達式。 [更多關於MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)。 (而'A.apply'就像'A.call'一樣,除了如果你想傳遞參數,你可以把它們當作一個類似數組的對象,而不是像你使用'call'那樣的單獨參數。) –

2

創建B實例後,您只需撥打inherit()

您需要在定義兩個函數後靜態調用inherit()一次。

您還需要在B的實例中調用A。請參閱my blog

+0

*「你還需要調用一個在B您的實例。」 *也許顯示瞭如何做到這一點,因爲它是不平凡的(當然,平凡的*做*,但是不知道如何去做)。 (我確定鏈接覆蓋它,但...) –

1

你沒有打電話給基構造。而且,如果只繼承一次類就足夠了。

var A = function() { 
 
    this.p1 = 2; 
 
}; 
 
A.prototype.f1 = function() { 
 
    return 7; 
 
}; 
 
var B = function() { 
 
    A.apply(this, arguments); 
 
}; 
 
inherit(A, B); 
 

 
function inherit(Child, Parent) { 
 
    Child.prototype = Object.create(Parent.prototype); 
 
    Child.prototype.constructor = Child; 
 
    
 
} 
 

 
var b = new B(); 
 
console.log(b.p1); // get undefined here