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中的繼承
感謝您的回答! T.J. Crowder,請你簡單解釋一下在調用'A.call(this)時會發生什麼;' –
@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'那樣的單獨參數。) –