Ashish Patel: Notes

Atom feed

Recently added: Conventional commits, Cli, Shortcuts, Subscriptions, Topic

Binding

Default binding

function display(){
 console.log(this); // 'this' will point to the global object
}
display(); 

Implicit binding

var obj = {
 name: 'Saurabh',
 display: function(){
   console.log(this.name); // 'this' points to obj
  }
};
obj.display(); // Saurabh
var name = "uh oh! global";
var outerDisplay = obj.display;
outerDisplay(); // uh oh! global
function setTimeout(callback, delay){
   callback(); // callback = obj.display;
}
setTimeout( obj.display, 1000 );

var name = "uh oh! global";
setTimeout( obj.display, 1000 );
// uh oh! global

Explicit hard binding

var name = "uh oh! global";
obj.display = obj.display.bind(obj); 
var outerDisplay = obj.display;
outerDisplay();
// Saurabh

Created 2019-04-08T05:58:16+00:00, updated 2024-10-27T19:38:33+00:00 · History · Edit