我对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
有没有办法在没有最后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.
显然,将变量传递给myFunction是一种选择……但这不是这个问题的重点。
谢谢。
https://stackoverflow.com/questions/456967
复制相似问题