0

the declaration of variable name = michelle in global scope is not being recognised by function sayNameForAll(), please let me know what is the issue.

function sayNameForAll() {
console.log(this.name);
}


var person1 = {
name: "Nicholas",
sayName: sayNameForAll
};


var person2 = {
name: "Greg",
sayName: sayNameForAll
};


var name = "Michael";

person1.sayName(); 
person2.sayName(); 
sayNameForAll();

this is the output of my code

Renzo Calla
  • 6,670
  • 2
  • 18
  • 35
Anam Nizami
  • 357
  • 2
  • 21

2 Answers2

2

It is working as expected in this script, the this variable can be changed in three ways:

  • when you call it inside of an object in that case would get the object .
  • When you use a constructor, class function.

  • And when you use call(), apply(), or bind(); methods.

Other wise will get the global object...

function sayNameForAll() {
console.log(this.name);
}


var person1 = {
name: "Nicholas",
sayName: sayNameForAll
};


var person2 = {
name: "Greg",
sayName: sayNameForAll
};


var name = "Michael";

person1.sayName(); 
person2.sayName(); 
sayNameForAll();
Renzo Calla
  • 6,670
  • 2
  • 18
  • 35
  • Do you think the issue here is may be due to hoisting? – Niladri Sep 12 '17 at 13:10
  • Not at all because at the time you call the sayNameForAll() the variable Michelle already exists in the global object.. – Renzo Calla Sep 12 '17 at 13:11
  • Yes thats what i noticed too but what if it is declared after `sayNameForAll();` – Niladri Sep 12 '17 at 13:12
  • It will still work because the execution of javascript is done in two phases, first the functions and variables take and space in memory, and after that the javascript execution takes place.. you can try moving it.. – Renzo Calla Sep 12 '17 at 13:15
  • Check how js is executed https://cedric-dumont.com/2015/10/31/compilation-and-execution-phases-of-simple-javascript-code/ – Renzo Calla Sep 12 '17 at 13:16
  • hey @RenzoCC, thanks mate, but issue is when i am running it in a node environment i get undefined object, however when i am running code snippet here on stackoverflow it is working as expected. any idea what that would be? Thanks – Anam Nizami Sep 12 '17 at 15:17
-1

The issue is within the context you run your function. In 2 first runs it goes inside context of the object, where you have 'this' internal variable. For the last one - you're trying to output 'this.name' but inside you've had only 'name'

Vyacheslav
  • 157
  • 4