本文介绍了设置“这个"容易变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Javascript 有很好的理解,只是我想不出设置this"变量的好方法.考虑:

I have a pretty good understanding of Javascript, except that I can't figure out a nice way to set the "this" variable. Consider:

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 行的情况下做到这一点?这很烦人...我尝试绑定一个匿名函数,我认为它很漂亮很聪明,但无济于事:

Is there a way to do this without the last 4 lines? It's rather annoying... I've tried binding an anonymous function, which I thought was beautiful and clever, but to no avail:

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 是一种选择……但这不是这个问题的重点.

Obviously, passing the variable into myFunction is an option... but that's not the point of this question.

谢谢.

推荐答案

JavaScript 中为所有函数定义了两种方法,call()apply().函数语法如下所示:

There are two methods defined for all functions in JavaScript, call(), and apply(). The function syntax looks like:

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

这些函数所做的是调用它们被调用的函数,将object 参数的值分配给this.

What these functions do is call the function they were invoked on, assigning the value of the object parameter to this.

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );

这篇关于设置“这个"容易变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:09