javascript - 失去对象内函数的作用域

标签 javascript jquery

我有一个问题,当对象 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/

相关文章:

javascript - 单击 anchor 时滚动 div 30px

javascript - 试图用 $.on(..) 替换 $.live(..)

javascript - 在 Angular 4 应用程序中使用 JQuery 插件

javascript - 为 Mozilla 创建鼠标事件

jquery - 如何重新加载 JQuery 网格保持滚动位置和折叠元素打开

jquery - 如何找到影响元素的 jQuery 脚本?

javascript - placeholder-not-working-for-internet-explorer 如果输入类型是密码,仍然显示 *********

javascript - 在选中的复选框上设置属性,否则删除属性

javascript - 访问对象内部的数组

JavaScript 表使用 sorttable 对重音字符进行排序