javascript - OO JavaScript - 避免 self = this

标签 javascript

有谁知道在以 OO 方式使用 JavaScript 时避免声明 var self = this 的方法吗?我经常看到它并且很好奇它是否只是您必须做的事情,或者是否真的有一种方法(也许是类库?)可以让您绕过它?我确实意识到为什么有必要(这具有功能范围)。但是您永远不知道那里可能有什么聪明的方法..

例如,我通常在 JS 中这样编写我的“类”:

function MyClass() {

}

MyClass.prototype = {

    firstFunction: function() {

        var self = this;

        $.ajax({
            ...
            success: function() {
                self.someFunctionCall();

            }
        });
    },

    secondFunction: function() {

        var self = this;

        window.setTimeout(function() {
            self.someOtherFunction();
        }, 1000);
    }

};

最佳答案

在您的第一个函数中,您可以这样做...

$.ajax({
    context: this,
    success: function() {
        this.someFunctionCall();

    }
});

在第二个中,您可以执行此操作,但您需要填充 .bind()在旧版浏览器中...

window.setTimeout(function() {
    this.someOtherFunction();
}.bind(this), 1000);

使用 jQuery,您也可以这样做...

window.setTimeout($.proxy(function() {
    this.someOtherFunction();
}, this), 1000);

关于javascript - OO JavaScript - 避免 self = this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641504/

相关文章:

javascript - 将主干 View 重新分配给新创建的 DOM 元素

javascript - 阶乘递归调用中的逻辑

javascript - 在初始化之前使用变量。 JS

javascript - 对象取消订阅错误: object unsubscribed

javascript - 循环遍历数组,但即使 “else” 语句为 true 也执行 “if” 语句 (javascript)

javascript - Protractor - 选择文本

javascript - D3 - 具有负值的路径

javascript - 触摸事件时 chrome 中的蓝色背景

javascript - 由于 php 结果更改 html 中的类和文本

javascript - 仅获取昨天和明天的日期,而不获取当天的日期和时间