javascript:如何更改"这个“;事件的作用域

javascript : how to change "this" scope on an event

本文关键字:这个 作用域 事件 quot 何更改 javascript      更新时间:2023-09-26

我已经打开了关于Function.prototype.bind的MDN文档,但我的脚本仍然无法工作。

我希望this引用添加到addEventListener的htmlElement。问题是,为什么我的this引用对象窗口。

这是没有绑定的脚本(http://jsbin.com/ejimor/1/edit):

var handle1 = document.getElementById('handle1'),
    handle2 = document.getElementById('handle2');
function doLogin() {
    alert(this);
}
function enterForm(ev) {
    if ( ev.which === 13 ) {
        doLogin();
    }
}
handle1.addEventListener('click', doLogin, false);
// this alert: [object HTMLButtonElement] this is what i want

handle2.addEventListener('keyup', enterForm, false);
// this alert: [object Window] this is what i do not want

那么,如何解决这个问题呢?

诀窍是,您希望在调用enterForm的上下文中调用doLogin,为此您可以使用callapply:

function enterForm(ev) {
    if (ev.which === 13) doLogin.call(this);
}

callapply确保它们被调用的函数内部的this被设置为传递给它们的第一个参数(例如,我们可以调用doLogin.call({x: 1})并获得[object Object]的警报)。

如果您总是希望在HTMLButtonElement的上下文中调用doLogin,则可以使用bind:将该函数替换为同一函数的绑定版本

function doLogin() { alert(this); }
doLogin = doLogin.bind(handle1);

bind创建了被调用函数的新版本,this永久绑定到传递给它的第一个参数

var newLogin = doLogin.bind({x: 1});

每次调用newLogin时,它都会被调用,其this上下文设置为我们的匿名{x: 1}对象(即使我们调用了newLogin.call(12)newLogin.apply(someObject)