0

I've seen many answers of how you can access an object's properties, but not how to access them from a function of that object. So my question is:

  • How do you access a property on an object, from a function, of a function of that object?

As an example, check out the code below...

// Wanted output:
1. Original settings // (a String)
2. Original settings // (a String)

Here's the code:

 class Animal {

    constructor(settings) {
        this.settings = settings;;
    }

    changeSettings(newSettings) {
        console.log("1. ", this.settings); // Prints OK. 

        checkOldSettings();

        function checkOldSettings() {
            console.log("2. ", this.settings); // This causes an error, as 'this' is undefined.
        }
    }
}

//==============================================================================

class Dog extends Animal {

}

//==============================================================================

let dog = new Dog("Origingal settings");   
dog.changeSettings("... Whatever settings, not important here...");

Cheers

daCoda
  • 3,583
  • 5
  • 33
  • 38
  • Use an arrow function instead – CertainPerformance Feb 14 '20 at 06:46
  • Your recommended question does not help... especially for new users. Mainly because I feel it's a different question, as that doesn't use polymorphism and also involves a callback - neither of which I use. Please reopen. – daCoda Feb 14 '20 at 22:16
  • If anyone can see this and are wondering, the solution is this: " checkOldSettings.call(this);" rather than "checkOldSettings();". The 'this' keyword inside checkOldSettings() is undefined without this change, so you must explicity define it via .call(). – daCoda Feb 14 '20 at 22:51
  • The problem is your `this` inside `checkOldSettings` is not referring to what you think it is, which is happening (mainly) because since `checkOldSettings` is a `function`, not an arrow function, it's not inheriting the `this` from the outer scope. This *is* a duplicate of the canonical - this is an extremely common issue – CertainPerformance Feb 15 '20 at 00:18

0 Answers0