我对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是一种选择……但这不是这个问题的重点。
谢谢。
发布于 2009-01-19 09:19:05
发布于 2011-07-09 02:57:41
如果你想将this
值‘存储’到一个函数中,以便以后可以无缝地调用它(例如,当你不能再访问该值时),你可以bind
它(但并不是所有的浏览器都提供):
var bound = func.bind(someThisValue);
// ... later on, where someThisValue is not available anymore
bound(); // will call with someThisValue as 'this'
发布于 2016-10-14 14:32:06
我关于如何绑定this
的搜索将我带到了这里,所以我发布了我的发现:在'ECMAScript 2015‘中,我们也可以使用箭头函数将其设置为。
请参阅:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
而不是:
function Person() {
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
this.age++;
}.bind(this), 1000);
}
我们现在可以这样做:
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
https://stackoverflow.com/questions/456967
复制相似问题