Reputation: 93
I am confused about javascript object methods on This and the implementation of ()=> instead of function(){},
Would you care to explain the behaviour of this: thanks
const obj = {
prop : 123,
test : function (){
console.log(this.prop);
},
test2 : ()=>{
console.log(this.prop);
},
}
console.log(test()); //results to 123
console.log(test2()); //results to undefined
Upvotes: 4
Views: 654
Reputation: 21
According to You Don't Know JS: ES6 & Beyond. Chapter 2. Syntax arrow functions are not only for shorter syntax for function declaration. It's about changing THIS behaviour.
In arrow function THIS is not dynamic, it's lexical.It points to surrounding scope, which is global so this.prop is undefined.
Example of correct using arrow function:
var controller = {
makeRequest: function(..){
btn.addEventListener( "click", () => {
// ..
this.makeRequest(..);
}, false );
}
};
We used arrow function for callback. So we can pass THIS from surrounding scope.
If we try to use regular function we have to pass THIS using var
:
var controller = {
makeRequest: function(..){
var self = this;
btn.addEventListener( "click", function(){
// ..
self.makeRequest(..);
}, false );
}
};
Upvotes: 1
Reputation: 4572
'this' keyword refers to the object context, when you call obj.test() that logs the property of that object (obj.prop). With the new method syntax introduced in ES6 we can omit the colon and the function keyword.
const obj = {
prop : 123,
test(){
console.log(this.prop);
},
test2: () => {
console.log(this.prop);
}
}
obj.test(); //123
obj.test2(); //undefined
If we use the 'this' keyword in a method then the value of 'this' is the calling object. Arrow functions inherently bind, an already defined 'this' value to the function itself that is NOT the calling object. In the code snippet above, the value of 'this' is the global object, or an object that exists in the global scope, which doesn’t have a 'prop' property and therefore returns undefined.
Upvotes: 3