我有一个问题,当对象 ana 在事件 $(window).resize
中运行时,我丢失了对对象 ana 的属性的引用$(window).resize
我可以尽力保持范围。
示例:
var testObject = {
init: function () {
this.divOriginal = $('.selector-tag');
this.resizeNow();
},
resizeNow: function () {
//some another code here....
//....
//..
$(window).resize(this.resizeUpdate.bind(this)); //without bind(this) the scope is window
},
resizeUpdate: function() {
console.log($(this));
var scrollWrapper = $(this)[0].divOriginal;//the only way to refer to the divOriginal
scrollWrapper.css('border','1px solid red');
}
}
testObject.init();
有更简洁的方法来访问对象的属性吗?
最佳答案
您可以简单地使用 this
而不是 $(this)
来访问该对象,因为您将对象绑定(bind)到了事件处理程序调用的方法。
请参阅MDN docs在 Function.prototype.bind() 上:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
关于javascript - 失去对象内函数的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577040/