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