除了无法找到设置“ this”变量的好方法之外,我对Javascript有很好的理解。考虑:
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
没有最后四行,有没有办法做到这一点?这很烦人……我试图绑定一个匿名函数,我认为它是美丽而聪明的,但无济于事:
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.
显然,将变量传递到myFunction是一个选项……但这不是这个问题的重点。
谢谢。
$.proxy(function, element)
以便每次调用该函数时,它将在element的上下文中。api.jquery.com/jquery.proxy