OO JavaScript - 避免自我=这个

Bri*_*asa 10 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);
    }

};
Run Code Online (Sandbox Code Playgroud)

小智 6

在你的第一个功能中你可以做到这一点......

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

    }
});
Run Code Online (Sandbox Code Playgroud)

在第二个,你可以这样做,虽然你需要.bind()在旧的浏览器中垫片...

window.setTimeout(function() {
    this.someOtherFunction();
}.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)

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

window.setTimeout($.proxy(function() {
    this.someOtherFunction();
}, this), 1000);
Run Code Online (Sandbox Code Playgroud)

  • @HunterMcMillen:在我的所有解决方案中,`this`将是对`MyClass`的引用. (5认同)