如何向前'this'javascript中函数调用的作用域

How forward the 'this' scope to a function call in javascript

本文关键字:函数调用 作用域 javascript this      更新时间:2023-09-26

如何转发引用正在调用事件侦听器的元素的this范围?

为例:

<input type=button value="Foo" id=mybutton>

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false)
    hover(); 
});

function hover(){
    this.value //undefined
}

使用JavaScript Function.callFunction.apply方法:

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false)
        hover.call(this); // `this` of the called hover points to this `this`
});

使用fn.call()fn.apply()来设置this的值。请参阅参考资料或在MDN申请。

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false) {
        hover.call(this); 
    }
});

.call().apply()都允许您指定this指针在被调用函数中的位置。

.call()允许您传递您希望被调用函数接收的特定附加参数,如下所示:

fn.call(this, true, "foo")`

.apply()用于当你想传递给被调用函数的参数是一个数组时,你只需要像这样传递参数数组:

var args = [true, "foo"];
fn.apply(this, args);

.apply()通常与内置参数对象一起使用,将现有的参数传递给被调用的函数(尽管也有其他原因使用它):

fn.apply(this, arguments);

你可以在你的hover()方法上使用function.Call()方法,它将调用hover方法。

Call方法的第一个参数是一个值,该值应该在调用方法中分配给this。

例如:

addEvent('mybutton','touchstart', function(){
if(window['touchmoved']==false)
{
}
    hover.call(this); 
});

function hover(){
    //this = touchstart event
}