Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function access to object property

Tags:

javascript

Why does the following code return just an empty string:

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

a.foo();
like image 874
user2598794 Avatar asked May 31 '26 17:05

user2598794


1 Answers

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);
like image 129
Rich Linnell Avatar answered Jun 03 '26 08:06

Rich Linnell