JavaScript - 始终访问特定对象的最佳方式

JavaScript - Best way to always access a specific Object

如果我创建一个对象如下:

window.Something = {
    X: function() {
        // statements...
    }
};

不使用 this 访问此对象的最佳方法是什么?

示例:

如果我使用以下方式调用 X 属性:

window.addEventListener("DOMContentLoaded", window.Something.X);

在这种情况下,使用 this 将访问 window 而不是 Something。 我想过这个方法,但我认为这是一种不好的做法。

window.Something = {
    X: function() {
        var This = window.Something;

        // statements...
    }
};

有一种隐式方法可以始终访问创建 属性?

real 对象

如果我没有正确理解你的问题,那么你可能想使用 bind:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

做这样的事情:

window.addEventListener("DOMContentLoaded", Something.X.bind(Something));

这将确保在对 Something.X 的调用中,this 指向 Something

更有用的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

使用 bind() 以适当的方式调用处理程序 this:

window.addEventListener("DOMContentLoaded", window.Something.X.bind(window.Something));

无需引用window(windows 始终是在全局范围内声明变量时的对象),也可以使用bind() 或包装函数。这将引用范围内的第一个对象。试试下面的代码

Something = {
    X: function()
    {
        // statements...
        console.log(this);

    }
};
window.addEventListener('click',function(){Something.X()});

没有人指出为什么会发生这种情况。

根据MDN

When attaching a handler function to an element using addEventListener(), the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

换句话说,this 指的是 window 对象,因为事件侦听器附加到 window 对象。例如,如果您将事件侦听器附加到 input 元素,则 this.name 将引用事件附加到的 input 元素的 name 属性。

Example Here

window.Something = {
  name: 'Some name',
  X: function() {
    console.log(this.name); // 'test'
  }
};

document.getElementById('target').addEventListener('input', Something.X);
<input id="target" name="test" />


正如其他人所指出的,您可以使用 bind() method:

来更改 this 的值

Example Here

window.Something = {
    name: 'Some name',
    X: function () {
        console.log(this.name); // 'Some name'
    }
};

window.addEventListener("DOMContentLoaded", Something.X.bind(Something));

或者,您也可以只在匿名函数中执行 X 方法。这将防止 addEventListener() 方法修改 this.

的值

Example Here

window.Something = {
    name: 'Some name',
    X: function () {
        console.log(this.name); // 'Some name'
    }
};

window.addEventListener("DOMContentLoaded", function () {
    Something.X();
});