-1

While trying to understand how javaScript resolve variable, i wrote this code:

const a = 0;
var obj = {a: 1, foo: function(){console.log(a);}};
obj.foo();

I know that javaScript, like most of the programming languages, use the lexical/static scope to resolving variables. But in this example, the lexical scope outside of foo function is obj scope and not global scope.

So why do i get output 0 instead of 1 ?

Moody
  • 43
  • 1
  • 7

4 Answers4

2

the lexical scope outside of foo function is obj scope and not global scope.

There is no such thing as "obj scope" or "object scope". In Javascript, every variable name (or identifier) is scoped to either a block (such as inside a loop, or inside a function block), or is global.

An object isn't a block. Putting a property on an object does not create a new identifier; referencing such a property name as if it were a standalone variable does not work, because it's not an identifier in scope.

The only time in which something like this would be possible would be if you used with and referenced the property as if it was a standalone variable inside the with block, but with should never be used.

const a = 0;
var obj = {
  a: 1,
  foo: function() {
    console.log(a);
  }
};
with (obj) {
  console.log(a);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

In an object with {a: 1} the 'a' is a string, not a variable. It does not assign 1 to 'a'. Instead it sets a key/value pair equivalent to { "a": 1 }.

It has nothing to do with scope. The variable a defined in the first line is the only variable of that name and never has its value changed in the code you gave.

Note also that you defined it as const meaning it cannot be assigned a different value.

Always Learning
  • 5,510
  • 2
  • 17
  • 34
1

If you need reference the a object property, is necessary use this.a, because a without this is the global variable.

const a = 0;

var obj = {a: 1, foo: function(){console.log(this.a);}};

obj.foo();
Oscar Velandia
  • 1,157
  • 1
  • 7
  • 9
1

Because there is only one a, and it's declared on your first line. In order to use this object's variables, you have to use this. For example:

const a = 0
var obj = { a: 1, foo: function() { console.log(this.a) } } 
obj.foo(); // 1

When you use this.a, that's the same thing, if you use obj.a outside of this object.

To understand this better, you can check the example below:

const mark = 10
const obj = {
  name: 'Sardor',
    mark: mark,
    setMark: function(num) { this.mark = num },
    getMark: function() { console.log(this.mark) }
}

obj.getMark() // 10
obj.setMark(8)
obj.getMark() // 8
console.log(mark) // 10

It means, that you filled mark by the date of num. Then you called .setMark() function of obj and changed its value to 8. But you didn't change the variable mark, that is outside of obj. That's why finnaly you have 8 in obj.mark and 10 in mark.

Advice: read more about this