[英]change the scope in this function to the invoker with jquery or vanilla javascript
Sample code with what I want to do is commented: 我想要做的示例代码被注释:
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;
}
}
});
Normally with underscore, I'd use its _.bind()
function to do this. 通常使用下划线,我会使用它的
_.bind()
函数来执行此操作。 The code I'm dealing with doesn't use underscore. 我正在处理的代码不使用下划线。 What's the best way to do this with vanilla JS or jQuery?
使用vanilla JS或jQuery执行此操作的最佳方法是什么?
JavaScript itself provides .bind
: JavaScript本身提供
.bind
:
myObj.doSomething({
callbackFn: function( result ) {
if ( result && result.retval !== null )
{
this.some_val = result.some_val;
}
}.bind(myObj); // <--
});
This is under the assumption that you cannot change the implementation of doSomething
. 这是假设您无法更改
doSomething
的实现。 If you can change it, see @10100111001's answer . 如果您可以更改它,请参阅@ 10100111001的答案 。
But you might as well use the code you currently have. 但是你也可以使用你目前拥有的代码。 I don't see a big benefit of using
.bind
here. 我没有看到在这里使用
.bind
好处。
Just for fun, a simple version of .bind
is pretty easy to implement yourself, should you find yourself in an environment that doesn't support it: 只是为了好玩,一个简单的
.bind
版本很容易实现,如果你发现自己处于一个不支持它的环境中:
function bind(f, thisValue) {
return function() {
return f.apply(thisValue, arguments);
};
}
var boundF = bind(f, myObj);
You can also do something like this where you can call
the callbackFn
in doSomething
with the proper this value. 你也可以这样做,你可以使用正确的值
call
doSomething
的callbackFn
。
var myObj = {}; myObj.doSomething = function (obj) { obj.callbackFn.call(this, {some_val: "test"}); } 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? this.some_val = result.some_val; } } }); console.log(myObj);
with
block is pretty much : with
块几乎是: function( result ) {
if ( result && result.retval !== null )
{
with(myObj){
some_val = result.some_val; // Even,no Need "this"
}
}
}
Even, No need this
甚至,不需要
this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.