【发布时间】:2010-10-02 04:49:00
【问题描述】:
我对 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 是一种选择......但这不是这个问题的重点。
谢谢。
【问题讨论】:
标签: javascript variables scope this