[英]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));
没有人指出为什么会这样。
根据MDN :
使用
addEventListener()
将处理程序函数附加到元素时,该值在处理程序内部的值是this
元素的引用。 它与传递给处理程序的事件参数的currentTarget
属性的值相同。
换句话说, this
是指window
对象,因为事件侦听器已附加到window
对象。 举例来说,如果你附加的事件侦听器的input
元素, this.name
要提到name
的属性input
该事件被附加到元素。
window.Something = { name: 'Some name', X: function() { console.log(this.name); // 'test' } }; document.getElementById('target').addEventListener('input', Something.X);
<input id="target" name="test" />
正如其他人所指出的那样,你可以改变的值this
使用bind()
方法 :
window.Something = { name: 'Some name', X: function () { console.log(this.name); // 'Some name' } }; window.addEventListener("DOMContentLoaded", Something.X.bind(Something));
另外,您也可以在匿名函数内部执行X
方法。 这将防止addEventListener()
方法修改this
的值。
window.Something = { name: 'Some name', X: function () { console.log(this.name); // 'Some name' } }; window.addEventListener("DOMContentLoaded", function () { Something.X(); });
无需引用窗口(在全局范围内声明变量时,窗口始终是对象),也可以使用bind()或包装函数。 这将引用范围中的第一个对象。 试试下面的代码
Something = {
X: function()
{
// statements...
console.log(this);
}
};
window.addEventListener('click',function(){Something.X()});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.