Reputation: 622
So I have been researching the keyword "this" in JS and im not sure if I fully understand it clearly. So in an attempt to understand the "this" keyword, I started off by creating a JS object and seeing if I can return a value based on some math executed with the this keyword. The following code below is my initial attempt:
let myObject = {
objectFunc: function() {
this.thing = 10;
},
addFunc: function(x) {
let result = this.thing + x;
return result;
}
}
console.log(myObject.addFunc(20));
So I expected this console log to return 30, however Im getting a "NaN" in the console. Can someone explain to me why? and also point me to some easier to understand documentation/explanation that isn't the MDN linked above?
Upvotes: -1
Views: 154
Reputation: 69
An easy to understand explanation would be that JavaScript 'this' keyword refers to the object it belongs to. The value of 'this' differs depending on how a function is invoked. There are four rules for 'this', in order of precedence that can be used to determine what 'this' gets bound to.
Rule 1. Default Binding: When invoking a function declaration 'this' keyword bounds to the global object.
Rule 2. Implicit Binding: When dot notation is used to invoke a function.
Rule 3. Explicit Binding: When .call(), .apply(), or .bind() are used on a function.
Rule 4. New Binding: When invoking a function by the new keyword, 'this' bounds to newly created object.
Upvotes: 0
Reputation: 191
You're on the right track. The reason why it's giving you NaN is because "this.thing" hasn't been defined yet. It's only defined when you call myObject.objectFunc()
first.
let myObject = {
objectFunc: function() {
this.thing = 10;
},
addFunc: function(x) {
let result = this.thing + x;
return result;
}
}
myObject.objectFunc()
console.log(myObject.addFunc(20));
Upvotes: 4