0

in this code below:

var a = 1;
var boat = { a:2, 
             innerBoat: {a:3, 
                        print(){console.log(a);},
                        },
            }; 
boat.innerBoat.print();  //output: 1

i don't understand why console.log(a); in print method returns the value 1.

Also, does the curly braces {} of the object referenced by boat creates a new private execution context in the stack at runtime ? (I know that only function calls create a new private execution context at runtime, but object creation confuses me, because they are originally a constructor call:

var boat = new Object();
Moody
  • 43
  • 6
  • You declared global variable a and this is returned in console.log. Use boat.a and return 2, use boat.innerBoat.a and return 3, use this.a and return 3. – Slawomir Dziuba Apr 30 '20 at 22:33

2 Answers2

1

In javascript, an object really is nothing more than a collection of data, like a dictionary in many other languages.

var boat = new Object(); just creates an empty object, as if you did var boat = {};

If you're looking for something more like , you may try using ES6 classes

var a = 0
class Boat {
  constructor() {
    this.a = 1;
  }
  print() {
    console.log(this.a);
  }
}
var boat = new Boat()
boat.print();  //output: 2
thesilican
  • 395
  • 2
  • 10
1

i don't understand why console.log(a); in print method returns the value 1.

It logs the value of the variable a.

The properties of the various objects around it which also have the name a are not variables. They can only be referenced as properties of an object.

const a = 1;
const object = {
    a: 2
};

console.log(a);
console.log(object.a)

See also How does the “this” keyword work? for how to access the property of an object that the method you are calling is attached to.


Also, does the curly braces {} of the object referenced by boat creates a new private execution context in the stack at runtime ?

No.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205