2011-08-31 182 views
1

为什么当我使用dojo.hitch函数并试图引用里面的“this”运算符时,它给了我引用错误的对象?Dojo.hitch()范围问题

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!!!! 
} 

感谢

+0

这不应该发生,不要相信你发布的内容与你在应用程序中尝试的内容相同。任何scnreenshots支持它? – Layke

+1

如果你把'console.log(dijit.byId(“widgetName”))'放在'hitch'之前,你确定它能够正确地返回吗?它是否会返回null?在这种情况下,'this'指的是'window'。 – pimvdb

+0

@Layke我知道这不应该发生,因此我的问题。一段时间以来,我一直在挠头。这是完全从我的应用程序复制/粘贴代码。我不知道你想在截图中看到什么?! – Ayyoudy

回答

6

根据你刚才表示什么,我现在可以安全地提供答案解释什么是错的。

当你做一个dojo.hitch()你不应该调用它的函数,而是调用函数的结果。也就是说,您需要提供dojo.hitch以引用该函数,而不是调用该函数的结果。

在你的榜样,你在呼唤tester()(其中调用函数tester)的dojo.hitch(),它调用tester一次内部。即使您拥有dojo.hitch()();,因为tester()未返回函数处理程序(但结果为tester,在这种情况下为undefined),因此hitch()();什么也不做。这可能会令人困惑,所以我会给你一个例子。

不要这样做:

dojo.hitch(背景下,处理程序())();

而是做到这一点:

dojo.hitch(上下文句柄)();

所以为了让你有非常可读的你可以这样做:

widget = dijit.byId("widgetName"); 
tester = function() { 
    console.log(this); 
} 

handle = dojo.hitch(widget, tester); 
handle(); 

你的错误是试图从dojo.hitch()内调用该函数。您的原始问题中也没有这个错误。

+0

谢谢。这似乎有帮助。但是如果我想将任何参数传递给测试者呢?即dojo.hitch(widget,test('myparam')); – Ayyoudy

+2

dojo.hitch()有一个我相信接受参数的第四个参数。无论是第四还是第三。我不记得了。查看具有如何通过dojo.hitch传递参数的dojo文档。 – Layke

+0

这非常有帮助。谢谢! – Ayyoudy