Difference between using variable self vs this

后端 未结 2 624
情深已故
情深已故 2021-02-09 00:50

I have been struggling with the use of these \"this\" with the .bind() method and the use of the variable \"self = this\". In getting two different results with those, so I\'m m

相关标签:
2条回答
  • 2021-02-09 01:06

    Be careful, self will always refer to the last instanciated object :

    var c1 = new Callback();
    var c2 = new Callback(); // overrides previous self
    

    Then following line actually sets c2.html_element :

    c1.set_html_element(html_element);
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

    That said, replacing this is completely useless in your case.

    0 讨论(0)
  • 2021-02-09 01:09

    If you're asking about the difference between self and this, then self is used as a reference to the original this. That means even if the content of this is changing, then self still contains the previous.

    Don't know if this is clear enough. If not take a look at What underlies this JavaScript idiom: var self = this? or Difference between self and this in javascript and when to use either of them.

    Also try to avoid using self as a global variable, because it's used by browsers nowadays for something. Sorry I don't remember what for - if someone could edit this info it that would be awesome.

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