除了无法找到设置“ this”变量的好方法之外,我对Javascript有很好的理解。考虑:var myFunction = function(){ alert(this.foo_variable);}var someObj = document.body; //using body as example objectsomeObj.foo_variable = "hi"; //set foo_variable so it alertsvar old_fn = someObj.fn; //store old valuesomeObj.fn = myFunction; //bind to someObj so "this" keyword workssomeObj.fn(); someObj.fn = old_fn; //restore old value没有最后四行,有没有办法做到这一点?这很烦人……我试图绑定一个匿名函数,我认为它是美丽而聪明的,但无济于事:var myFunction = function(){ alert(this.foo_variable);}var someObj = document.body; //using body as example objectsomeObj.foo_variable = "hi"; //set foo_variable so it alertssomeObj.(function(){ fn(); })(); //fail.显然,将变量传递到myFunction是一个选项……但这不是这个问题的重点。谢谢。
3 回答
HUH函数
TA贡献1836条经验 获得超4个赞
如果您想将该this值“存储” 到一个函数中,以便以后可以无缝调用它(例如,当您再无权访问该值时),则可以bind(尽管并非在所有浏览器中都可用):
var bound = func.bind(someThisValue);
// ... later on, where someThisValue is not available anymore
bound(); // will call with someThisValue as 'this'
添加回答
举报
0/150
提交
取消