简体   繁体   中英

JavaScript function access to object property

Some stupid question but.. Why the following code returns me just an empty string:

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

a.foo();

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);

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

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);
    });
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM