'JavaScript function access to object property

Why does the following code return just an empty string:

var a = {
     name:"321",
     foo: function(){
        console.log(name);
    }
}

a.foo();


Solution 1:[1]

because you haven't scoped name to anything so it's looking for a global variable. try replacing

console.log(name);

with

console.log(this.name);

Solution 2:[2]

you can use this keyword like this - console.log(this.name); .In result of your code, you see an empty string and not a undefined error because window.name variable already exists and has nothing to do with the name variable in your object

Solution 3:[3]

Following comments on Rich Linnell answer:

foo is for the object's function scope exemple, and bar for callbacks's scopes.

Code:

var foo = "global",
    bar = "global",
    a = {
    foo: (callback) => {
        // var foo = 'local';
        console.log('foo: ' + foo);
        callback();
    }
};

(() => {
    // var bar = "parent";
    a.foo(() => {
        // var bar = "local";
        console.log('bar: ' + bar);
    });
})();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rich Linnell
Solution 2 matharumanpreet00
Solution 3