0

I know this is empty in the beginning of a contructor function, and gets filled until it's automatically returned.

function Elf(_name, _weapon) {
 
  //empty this
 console.log('this a', this); // {}

 this.name = _name;
 this.weapon = _weapon;
 
 // this with props
 console.log('this b', this); // {name: "Sam", weapon: "bow"}
}

let sam = new Elf("Sam", "bow"); 

In the node console and this snippet, the result is what i expected:

this a {}
this b { "name": "Sam", "weapon": "bow" }

But in the Chrome's console, i get:

   this a Elf {}
name: "Sam"
weapon: "bow"
__proto__: Object

this b Elf {name: "Sam", weapon: "bow"}
name: "Sam"
weapon: "bow"
__proto__: Object

why are those name and weapon properties already filled? If you'r gonna mention hoisting, and that the reference to this becomes global, why the difference between the two logs?

  • It's an issue with the way chrome logs things [see also](https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch) | [and this](https://stackoverflow.com/questions/23392111/console-log-async-or-sync) – Mark Jun 30 '19 at 17:45
  • Possible duplicate of [Wrong value in console.log](https://stackoverflow.com/questions/11214430/wrong-value-in-console-log) and [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440) – adiga Jun 30 '19 at 17:46
  • `this a Elf {}` seems to be the expected result? – Bergi Jun 30 '19 at 18:32

1 Answers1

-2

Try in chrome console the following code

function Elf(_name, _weapon) {
    console.log('before', this.name);

    this.name = _name;
    this.weapon = _weapon;

    console.log('after', this.name);
}

let sam = new Elf("Sam", "bow"); 

You will get expected result. Maybe logging in chrone console is not 'immediate' and thus, this is filled with value before displaying.

farvilain
  • 2,552
  • 2
  • 13
  • 24