2012-01-07 43 views
0

我有一些問題,試圖從JS原型繼承。 問題是,在子類中,如果我是從Master派生的,則從Master派生的initX方法不會被稱爲通過「this」的方法。在Firbug原型在JS:訪問父我們尚未派生的方法

function master() {}; 
function sub() {}; 

master.prototype = { 
    init: function() { 
     console.log('Master Init!'); 
     this.initX();     // This is where the error is thrown 
    }, 
    initX: function() { 
     console.log('Master InitX'); 
    } 
}; 

sub.prototype = new master(); 
sub.prototype.constructor = sub; 
sub.parent = master.prototype; 

sub.prototype.init = function() { 
    sub.parent.init.call(); 
    console.log('Sub Init'); 
} 

var subby = new sub(); 
subby.init(); 

錯誤消息:

TypeError: this.initX is not a function 

所以基本上母親INIT被稱爲但隨後在母親的init拋出,因爲this.initX的錯誤。

任何任何想法?

回答

1

您實際上沒有通過this值,因此它將等於init中的windowwindow.initX不存在。

.call()因爲它的立場是相當無用 - 使用下面的代替:

sub.parent.init.call(this); // set `this` inside `init`, so that 
          // you'll be calling `initX` on the instance 

如果你想通過參數以及,通過一切都一起被.applyarguments相結合的一種通用方式:

sub.parent.init.apply(this, arguments); 
+0

非常感謝!這工作! – 2012-01-07 15:57:27