138 javascript variables scope this
我对Javascript有很好的理解,除了我找不到设置"this"变量的好方法.考虑:
var myFunction = function(){
alert(this.foo_variable);
}
var someObj = document.body; //using body as example object
someObj.foo_variable = "hi"; //set foo_variable so it alerts
var old_fn = someObj.fn; //store old value
someObj.fn = myFunction; //bind to someObj so "this" keyword works
someObj.fn();
someObj.fn = old_fn; //restore old value
Run Code Online (Sandbox Code Playgroud)
没有最后4行,有没有办法做到这一点?这很烦人......我试过绑定一个匿名函数,我觉得这个函数漂亮而聪明,但无济于事:
var myFunction = function(){
alert(this.foo_variable);
}
var someObj = document.body; //using body as example object
someObj.foo_variable = "hi"; //set foo_variable so it alerts
someObj.(function(){ fn(); })(); //fail.
Run Code Online (Sandbox Code Playgroud)
显然,将变量传递给myFunction是一个选项......但这不是这个问题的重点.
谢谢.
For*_*ood 219
为JavaScript中的所有函数定义了两种方法call(),和apply().函数语法如下:
call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);
Run Code Online (Sandbox Code Playgroud)
这些函数的作用是调用它们被调用的函数,并将object参数的值赋给它.
var myFunction = function(){
alert(this.foo_variable);
}
myFunction.call( document.body );
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 55
我想你正在寻找call:
myFunction.call(obj, arg1, arg2, ...);
Run Code Online (Sandbox Code Playgroud)
这就要求myFunction与this设置为obj.
还有一个稍微不同的方法apply,它将函数参数作为数组:
myFunction.apply(obj, [arg1, arg2, ...]);
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 18
如果你想将this值"存储" 到一个函数中,以便以后可以无缝地调用它(例如,当你再也无法访问该值时),你可以使用bind它(不是在所有浏览器中都可用):
var bound = func.bind(someThisValue);
// ... later on, where someThisValue is not available anymore
bound(); // will call with someThisValue as 'this'
Run Code Online (Sandbox Code Playgroud)