Why does the following code return 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);
this, the code will search a scoped variable named name, and another property of the same object isn t considered inside the scope. If you had a global var name, you would see it value.a.foo, then continue in the global code. I don't know the reason JS act like that though.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);
});
})();
console.log(this.name);nametothis.nameand you should see321printed!