Skip to content

Instantly share code, notes, and snippets.

@lin
Created November 12, 2018 08:45
Show Gist options
  • Save lin/007ca4221ac9858bfc3a2bf901cce1ff to your computer and use it in GitHub Desktop.
Save lin/007ca4221ac9858bfc3a2bf901cce1ff to your computer and use it in GitHub Desktop.

1, when you define a function, it binds this to the object it might belongs to.

const obj = {
  method: function() {
    // this is obj
  }
};

//otherwise:
function(){
  //this is belong to window by default
}

// if it is a callback function
callback(function(){ 
  //this is belongs to window by default
})

2, detailed example:

var module = {
  method: function() {
    // this is module:
    console.log("In method: this is ", this);
    this.callback(function(){
      // this is window
      console.log("In callback: this is ", this);
      (function(){
        // this is window
        console.log("In anywhere else: this is ", this);
      })();
    });
  },
  callback: function(func){
    func();
  }
};
module.method();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment