1

why Function.prototype.call() executed before console.log()?

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food() {
  console.log(this)
  Product.call(this, 'cheese', 5);
  this.category = 'food';
}
new Food()

enter image description here

sina
  • 98
  • 6
  • It's not, it's just the console is a live view. – Keith Jun 17 '21 at 20:13
  • 1
    And `this.category = 'food';` is ran before you open it – Samathingamajig Jun 17 '21 at 20:14
  • Hover over the blue **i** symbol and it'd inform you of this behaviour. If you print an object to the console and expand it later, you'd see its *current state*, not the state it was at the time of logging. The logged reference is live. – VLAZ Jun 17 '21 at 20:17

1 Answers1

1

It's not executing before the console.log, as others mentioned, it is caused by the live reference to that object, so you will always see the newest value of the object.

Check the example

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food() {
  console.log(this)
  Product.call(this, 'cheese', 5);
  console.log(this)
  this.category = 'food';
}
new Food()

Update

You can see the current value if you are not opening the object (the first is an empty object {}, the second got values), I pointed it with arrows. If you open the object you will see the live reference, which is the same for both logs.

enter image description here

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39