假設我有一個javascript類Library1.B
,它從同一個庫中的超類繼承methodA
。
假設我想將Library1
克隆到Library2
中,以便製作我自己的版本,並稍微覆蓋Library1.B
的繼承的methodA
以改進它。天真,我闡述了這樣做:Javascript - 在克隆庫中重寫繼承的方法
/* Library 1 */
var Library1 = {};
Library1.A = function() {
console.log("A's constructor called");
};
Library1.A.prototype.methodA = function() {
console.log("methodA called with arguments", arguments);
//heavy computation
};
Library1.B = function() {
Library1.A.call(this);
//Set a few other properties exclusive to B
};
Library1.B.prototype = Object.create(Library1.A.prototype);
/* Library 2 */
var Library2 = Library1;
Library2.B.prototype.methodA = function() {
console.log("Before invoking methodA()");
Library1.B.methodA.apply(this, arguments);
console.log("After invoking methodA()");
};
var o1 = new Library1.B();
o1.methodA(1, 2, 3);
var o2 = new Library2.B();
o2.methodA(4, 5, 6);
(的jsfiddle here)
預計日誌上面:
A's constructor called
methodA called with arguments [1, 2, 3]
A's constructor called
Before invoking methodA()
methodA called with arguments [4, 5, 6]
After invoking methodA()
相反,我得到這樣的:
A's constructor called
Before invoking methodA()
Uncaught TypeError: Cannot read property 'apply' of undefined
因此很明顯, o1
,儘管是用構建的對象0的構造函數(它又調用Library1.A
的構造函數),已經使用Library2
的覆蓋的methodA
;它然後在Library1.B.methodA.apply
電話崩潰,我想因爲Library1.B
沒有它自己的methodA
,而是從Library1.A
繼承。
我的意思是,當我寫Library1.B.methodA
實際上是「擡頭Library1.B
的原型鏈,直到找到定義methodA
,然後調用它this
這些arguments
」是什麼。
什麼是實現這一目標的正確方法?
你認爲這行做了什麼'var Library2 = Library1'? – elclanrs 2014-10-05 12:23:08
我看到你在哪裏:我期望'Library2'成爲'Library1'的一個*拷貝*,但我想它只是成爲對'Library1'的引用,所以在'Library2'上調用的任何東西實際上都會被調用' Library1'?我會嘗試編輯小提琴,看看問題是否仍然存在,謝謝你的提高。 – 2014-10-05 12:49:43
好吧,編輯jsFiddle(http://jsfiddle.net/axedre/puposqs5/1/),但仍然沒有骰子:與以前一樣的錯誤。 :( – 2014-10-05 12:57:38