简体   繁体   English

Javascript - 如何为函数设置'this'变量

[英]Javascript - how do i set the 'this' variable for a function

I have a function which takes a callback function. 我有一个带回调函数的函数。 How can I set the 'this' variable of the callback function? 如何设置回调函数的'this'变量?

eg. 例如。

function(fn){
    //do some stuff
    fn(); //call fn, but the 'this' var is set to window
    //, how do I set it to something else
}

you can execute a function in the context of an object using call : 您可以使用调用在对象的上下文中执行函数:

fn.call( obj, 'param' )

There's also apply 这也适用

Only difference is the syntax for feeding arguments. 唯一的区别是提供参数的语法。

You can use either apply() or call( ). 您可以使用apply()call( )。

Either allows you to execute a function with your choice of what this is inside the function. 要么让你与你选择的是什么执行功能this是里面的功能。 Apply takes the arguments for the function as an array, while call allows you to specify them individually. Apply将函数的参数作为数组,而call允许您单独指定它们。

funct.call(objThatWillBeThis, arg1, ..., argN);

要么

funct.apply(objThatWillBeThis, arrayOfArgs);

You can use either .call() or .apply(). 您可以使用.call()或.apply()。 Depending on your requirement. 根据您的要求。 Here is an article about them. 是一篇关于他们的文章。

Basically you want: 基本上你想要:

function(fn){
    //do some stuff
    fn.call( whateverToSetThisTo ); //call fn, 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM