设置“this”容易变? [英] Set "this" variable easily?

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

问题描述

我对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中的函数, 调用() 应用() 。函数语法如下:

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

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

这些函数的作用是调用它们被调用的函数,赋值对象参数 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 );

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆