What underlies this JavaScript idiom: var self = this?

前端 未结 10 1884
长情又很酷
长情又很酷 2020-11-22 03:37

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:

function Note() {
  var self = this;

  var note = document.createElement(\'d         


        
相关标签:
10条回答
  • 2020-11-22 04:27

    The variable is captured by the inline functions defined in the method. this in the function will refer to another object. This way, you can make the function hold a reference to the this in the outer scope.

    0 讨论(0)
  • 2020-11-22 04:32

    Actually self is a reference to window (window.self) therefore when you say var self = 'something' you override a window reference to itself - because self exist in window object.

    This is why most developers prefer var that = this over var self = this;

    Anyway; var that = this; is not in line with the good practice ... presuming that your code will be revised / modified later by other developers you should use the most common programming standards in respect with developer community

    Therefore you should use something like var oldThis / var oThis / etc - to be clear in your scope // ..is not that much but will save few seconds and few brain cycles

    0 讨论(0)
  • 2020-11-22 04:34

    Yes, you'll see it everywhere. It's often that = this;.

    See how self is used inside functions called by events? Those would have their own context, so self is used to hold the this that came into Note().

    The reason self is still available to the functions, even though they can only execute after the Note() function has finished executing, is that inner functions get the context of the outer function due to closure.

    0 讨论(0)
  • 2020-11-22 04:38
    function Person(firstname, lastname) {
      this.firstname = firstname;
    
      this.lastname = lastname;
      this.getfullname = function () {
        return `${this.firstname}   ${this.lastname}`;
      };
    
      let that = this;
      this.sayHi = function() {
        console.log(`i am this , ${this.firstname}`);
        console.log(`i am that , ${that.firstname}`);
      };
    }
    
    let thisss = new Person('thatbetty', 'thatzhao');
    
    let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
    

    thisss.sayHi.call(thatt);

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