Ayy*_*udy 2 javascript dojo scope
为什么当我使用dojo.hitch函数并尝试在其中引用"this"运算符时,它会让我引用错误的对象?
console.debug(dijit.byId("widgetName")); //works as expected and prints out the window object
dojo.hitch(dijit.byId("widgetName"), tester())(); //this should be executing the tester function in the scope of the widget object
function tester() {
console.debug(this); //prints out the Javascript Window object instead of the widget object!!!!
}
Run Code Online (Sandbox Code Playgroud)
谢谢
根据您刚刚展示的内容,我现在可以安全地提供解释错误的答案.
当你这样做时,你不dojo.hitch()应该调用它内部的函数,而是调用函数的结果.也就是说,您需要提供dojo.hitch对函数的引用,而不是调用该函数的结果.
在您的示例中,您正在调用tester()(调用函数tester)dojo.hitch(),调用tester一次.即使你dojo.hitch()();因为tester()没有返回一个函数处理程序(但tester在这种情况下是结果undefined),hitch()();它什么都不做.这可能会令人困惑,所以我将向您展示一个例子.
不要这样做:
dojo.hitch(context,handler())();
而是这样做:
dojo.hitch(context,handler)();
因此,为了使您具有可读性,您可以这样做:
widget = dijit.byId("widgetName");
tester = function() {
console.log(this);
}
handle = dojo.hitch(widget, tester);
handle();
Run Code Online (Sandbox Code Playgroud)
你的错误是试图从内部调用函数dojo.hitch().您的原始问题中也没有出现此错误.
| 归档时间: |
|
| 查看次数: |
5737 次 |
| 最近记录: |