How can a member function access member variables?

Viewed 36

In the code snippet below I am trying to access name which is a member variable from sayHi which is a member function. How can I do that?

obj = {
    name:"John",
    sayHi: ()=>{
        console.log("Hi " + name);
    }

}
obj.sayHi();
2 Answers

Arrow function expressions are best suited for non-method functions. It seems you want sayHi to use the name property of obj. As such, you want to use sayHi as a method, and in this case an arrow function is not appropriate for the purpose.

If you change the arrow function expression to an anonymous function, then you can use this.name to refer to the name property of the object on which you will call the sayHi function:

obj = {
    name: "John",
    sayHi: function() {
        console.log("Hi " + this.name);
    }    
}
obj.sayHi();  // prints "Hi John"

A good resource about arrow function expressions is this page on developer.mozilla.org.

You don't have to use an anonymous function like @janos says. When you're using arrow functions, this refers to the class or context that your object is defined in. So you can call into name by calling this.obj.name like so:

obj = {
    name:"John",
    sayHi: ()=>{
        console.log("Hi " + this.obj.name);
    }

}
obj.sayHi();
Related