gpt4 book ai didi

javascript - 使用 jquery 或 vanilla javascript 将此函数的范围更改为调用程序

转载 作者:行者123 更新时间:2023-11-30 11:53:00 24 4
gpt4 key购买 nike

注释了我想做的示例代码:

 myObj.doSomething({
callbackFn: function( result ) {
if ( result && result.retval !== null )
{
// I want to assign the values on result.retval to myObj
// but `this` is not equal to myObj.
// is it correct to just do this?
myObj.some_val = result.some_val;
}
}
});

通常带有下划线,我会使用它的 _.bind() 函数来做到这一点。我正在处理的代码不使用下划线。使用普通 JS 或 jQuery 执行此操作的最佳方法是什么?

最佳答案

JavaScript 本身提供了.bind :

myObj.doSomething({
callbackFn: function( result ) {
if ( result && result.retval !== null )
{
this.some_val = result.some_val;
}
}.bind(myObj); // <--
});

这是假设您无法更改 doSomething 的实现。如果可以更改它,请参阅 @10100111001's answer .

但是您也可以使用当前拥有的代码。我没有看到在这里使用 .bind 有什么大的好处。


只是为了好玩,.bind 的简单版本很容易自己实现,如果您发现自己处于不支持它的环境中:

function bind(f, thisValue) {
return function() {
return f.apply(thisValue, arguments);
};
}

var boundF = bind(f, myObj);

关于javascript - 使用 jquery 或 vanilla javascript 将此函数的范围更改为调用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38920552/

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