我試圖從require
d節點模塊調用具有特定this
對象的方法。據我所知,有三種方法可以做到這一點,.bind(obj)(args)
,或.call(obj, arg1, ...)
,或.apply(obj, aryArgs)
。我目前正在使用bind
,但我已經嘗試了所有三個相同級別的不成功。爲什麼我的界限被忽略了?
這是我運行的呼叫:
var library = require("./library.js");
// ...
requestHandler.bind(library)(req);
requestHandler
從這個文件中導出的status
函數的引用:
exports.status =() => {
console.log(this);
this.render({text: "status ok"});
};
exports.paramSwitching =() => {
this.render("rendered via param switching");
};
exports.json =() => {
this.render({json: {this: 'renders', as: 'json'}});
};
exports.view =() => {
this.render({view: true, locals: {text: 'hi'}});
};
我想這個工作,使調用status
函數時將library
作爲其this
對象,因爲這是定義render
的地方。然而,console.log
聲明顯示this
作爲文件保存status
的評價的內容,即
{ status: [Function],
paramSwitching: [Function],
json: [Function],
view: [Function] }
這裏發生了什麼,以及如何解決這個問題? (或者,如果我不能,因爲Node有點奇怪,是否有解決方法?)
請包括定義'requestHandler'的代碼,因爲它不是對出口中'.status'方法的引用,而是整個'exports'對象 – Pineda
@Pineda:它已包含在內。仔細閱讀問題 – slebetman
像往常一樣,每當有一個誤解'this',我會指出讀者對我這個問題的回答:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword在JavaScript中的對象文字/ 13441628?s = 1 | 4.1585#13441628 – slebetman