Scope of “this” in JavaScript

后端 未结 4 1911
春和景丽
春和景丽 2021-01-05 03:27

I have a JavaScript class that looks like this:

function SomeFunction()
{
    this.doSomething(function()
    {
        this.doSomethingElse();
    });

             


        
相关标签:
4条回答
  • 2021-01-05 04:09

    That is the correct and commonly-accepted workaround. It's sort of kludgy but it's what everybody does. Typically this extra variable is named self, as in:

    function SomeFunction()
    {
        var self = this;
    
        this.doSomething(function()
        {
            self.doSomethingElse();
        });
    
        this.doSomethingElse = function()
        {
    
        }
    }
    
    0 讨论(0)
  • 2021-01-05 04:17

    It's also worth mentioning that the next version of ECMAScript (the language spec for JavaScript) is going to introduce Function.bind(), which will let you specify a permanent context for a function.

    0 讨论(0)
  • 2021-01-05 04:25

    This commenter had what I was looking for (although the other answers are good too):

    @Jon Kruger See this, check out their article for call, too: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply– Jonathon 44 mins ago

    0 讨论(0)
  • 2021-01-05 04:34

    this has dynamic "scope". That means that it is set up by whatever binds it, and this is bound by a "method call". That is, any time in your program you see this: w.f() then while f is executed, this is dynamically bound to f, even if f had this in its lexical scope.

    Most JavaScript frameworks provide some facilities for dealing with this exact problem. With Prototype.js (for example) you can do this:

    this.doSomething(function() { this.doSomethingElse(); }.bind(this));
    

    Your "hack" however is fine. I usually do a (function (self) { ... })(this) around any functions that I need a lexically-scoped this-like variable.

    0 讨论(0)
提交回复
热议问题