2

Why does the following code return just an empty string:

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

a.foo();
4
  • 3
    console.log(this.name); Commented Jul 26, 2016 at 16:19
  • Check the browser's console. It should print nothing. Change name to this.name and you should see 321 printed! Commented Jul 26, 2016 at 16:19
  • @Noah, actually it will print something. Empty string! See window.name Commented Jul 26, 2016 at 16:21
  • Good catch @PatrickRoberts Commented Jul 26, 2016 at 16:25

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

6 Comments

I understand that 'this.name' works. I just wonder why function hasn't access to 'name' property.
@user2598794 Because without 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.
@DrakaSAN Why 'name' in the object isn't considered inside the scope? And where it starts the search?
@user2598794 In your example, it start inside a.foo, then continue in the global code. I don't know the reason JS act like that though.
JS is built on functions and their closures. The associated object can easily change, and a single function could be in multiple objects.
|
1

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

Comments

1

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

2 Comments

I commented out only the '1' name and it prints me "name: 3". And if I commented '1' and '3' it prints empty string. Looks like it doesn't see function scope at all.
@user2598794: Ah, yes, I forgot that in that case it skip to the global scope, unlike callbacks. I ve edited my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.