更新答:
從下面的評論,回覆我說statment應this.log()
工作:
嘛,所以這就是事情。當我在兒童的測試功能,this
是一個空的對象,所以我假設在某個地方我沒有得到適當的範圍。
你沒有顯示你是如何打電話test
,但我懷疑這是問題所在。只要你通過Child
實例調用它:
var c = new Child();
c.test();
...然後內通話,this
將子實例,這將繼承(間接)與其log
屬性Parent.prototype
對象。
但你怎麼稱呼它是重要的。這是行不通的,例如:
var c = new Child();
var f = c.test;
f();
如果你這樣做,在調用函數中,this
將是全局對象(或undefined
如果在嚴格模式是),而不是一個Child
實例。這是因爲在JavaScript中,this
主要由函數的調用方式來設置,並且像這樣調用它並不會將this
設置爲您想要的值。
這會影響回調,因爲在c.test
傳遞的回調:
someFunctionThatUsesACallback(c.test);
...意味着代碼回撥不會將this
你。
如果你需要做的是,Function#bind
將幫助:
var f = c.test.bind(c); // Returns a version of c.test that, when called,
// will have `this` set to `c`
f(); // Works, `this` is the `Child` instance
而且類似:
someFunctionThatUsesACallback(c.test.bind(c));
更多(在我的博客):
原來的答案:
如果設置了原型層次正確,並Child.prototype
沒有它log
(你不把情況一log
屬性),那麼你應該可以使用this.log();
就好了。如果你不能,那麼層次結構尚未正確設置。
我不知道是什麼util.inherits
的做法,但Child
和Parent
之間建立的關係,正確並不複雜:
function Parent() {
}
Parent.prototype.log = function() {
console.log("log called");
};
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // This line is largely optional, but a good idea
// Usage
var c = new Child();
c.log(); // "log called"
但是,如果你重寫你的Child.prototype
log
或分配log
屬性實例,並且您想要使用Parent
的版本log
,那麼當然,您不能僅僅使用this.log()
,因爲該屬性不再指代Parent.prototype.log
了。
當你需要調用的東西父版本(我稱他們爲「supercalls,」我不認爲這是原始的),你必須做更多的工作:
我通常建立層次結構是這樣通過將父類的構造成一個功能我用它來打造孩子,如:
var Child = (function(Super) {
var pp = Super.prototype;
function Child() {
}
Child.prototype = Object.create(pp);
Child.prototype.doSomething = function() {
// Call `log` with appropriate `this`
pp.log.call(this);
};
return Child;
})(Parent);
通過經常使用這種模式,我避免了不得不寫Parent
的Child
代碼中(我用的是Super
ARG代替),所以如果我需要重設Child
,我只需更改我傳入該函數的內容。
因爲這是相當醜陋的(例如,它是在Child
頂部,它從Parent
派生不清楚,因爲Parent
是在底部)和涉及樣板代碼,我不覺得有必要每次都寫一遍,我寫了一個簡單的輔助腳本它,我打電話Lineage
,這使得它看起來是這樣的:
var Child = Lineage.define(Parent, function(p, pp) {
p.doSomething = function() {
// Call `log` with appropriate `this`
pp.log.call(this);
};
});
注意Lineage
通行證在Child
和Parent
原型既作爲參數,使之簡潔使用它們(因爲你得到挑選這些argumetn名稱,您可以使用任何適用於您的術語 —我使用p
作爲創建的「類」的原型[Child
在上面],和pp
爲父母的原型等)。
不是那些做都失敗,因爲'this'在調用'log時有錯誤的值'? –
是的,'this.log()'只是失敗並且崩潰了服務器,但我把它放在了我想要的東西上。 – incutonez