What does “self” mean in javascript?

前端 未结 5 1851
-上瘾入骨i
-上瘾入骨i 2020-12-02 23:04

I read here that \"self Refers to the current window or form\".

Self does not seem to refer to the current form in this case:

5条回答
  •  日久生厌
    2020-12-03 00:01

    self is not a reserved keyword or standard type, but has become a defacto standard name when for keeping reference to an object for closures.

    Here we create a closure to pass to setTimeout(). When that closure is executed, this will refer to the global object. To keep a reference to the foo object doLater was originally called on, a var named self is used. It could be anything but 'self' has meaningful semantics.

    Foo.prototype.doLater = function() {
      var self = this; // current object
    
      window.setTimeout(function() { self.doSomething(); }, 1000);
    }
    
    new Foo().doLater();
    

提交回复
热议问题