gpt4 book ai didi

javascript - Dojo.hitch() 范围问题

转载 作者:行者123 更新时间:2023-11-29 16:24:40 24 4
gpt4 key购买 nike

为什么当我使用 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!!!!
}

谢谢

最佳答案

根据您刚刚展示的内容,我现在可以安全地提供答案来解释问题所在。

当你执行dojo.hitch()时,你不应该调用其中的函数,而应该调用函数的结果。也就是说,您需要向 dojo.hitch 提供对要挂接的函数的引用,而不是调用该函数的结果。

在您的示例中,您正在 dojo.hitch() 内部调用 tester() (它调用函数 tester),它调用测试器一次。即使您有 dojo.hitch()(); 因为 tester() 不返回函数处理程序(而是返回 tester 的结果,在这种情况下,未定义),hitch()();什么也不做。这可能会让您感到困惑,所以我将通过一个示例向您展示。

不要这样做:

dojo.hitch( context, handler() )();

而是这样做:

dojo.hitch( context, handler )();

因此,为了使您的内容非常可读,您可以这样做:

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

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

您的错误是尝试从 dojo.hitch() 内调用该函数。您原来的问题中也不存在此错误。

关于javascript - Dojo.hitch() 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7258286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com