Use of 'this' in JS
Dan Abramov question
by meetravi
JavaScript
/*
These two snippets are different:
// 1
obj.method(); // this binds to the object in this instance
// 2
var method = obj.method;
method(); // this binds to the window method in this instance as window.method(); indirectly
Learn why and you’ll understand JavaScript.
https://twitter.com/dan_abramov/status/790858537513656320
Answer:
// 1
obj.method(); // this binds to the obj in this instance
any method will get binds to the left of the object it is called
In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.
// 2
var method = obj.method;
method();// turns out to be window.method();
*/
var obj = {
func : function() {console.log("this",this);
return (this.name)
},
name: 'Ravi'
};
console.log("1", obj.func())
var method = obj.func;
console.log("2", method())