1

I'm studying Javascript, and I found this example on my book

function sayNameForAll(label) {
    console.log(label + ":" + this.name);
}
var person1 = {
    name: "Nicholas"
};
var person2 = {
    name: "Greg"
};
var name = "Michael";
sayNameForAll.call(this, "global");
sayNameForAll.call(person1, "person1");
sayNameForAll.call(person2, "person2");

This outputs:

"global:Michael"
"person1:Nicholas"
"person2:Greg"

I understand how call works, but the output of sayNameForAll.call(this, "global"); isn't global:Michael but global:result.

this is code http://jsfiddle.net/rho3zyb4/

monkeyUser
  • 4,301
  • 7
  • 46
  • 95

4 Answers4

0

You're running this code in jsfiddle, aren't you: http://jsfiddle.net/4g8q9yor/ - jsfiddle has assigned the iframe name which your javascript outputs to as result - so you're actually getting the DOM iframe name.

enter image description here

Create the file on your local machine and you'll see the correct output or try it elsewhere: http://js.do/code/48143 outputs:

global:Michael
person1:Nicholas
person2:Greg
Prisoner
  • 27,391
  • 11
  • 73
  • 102
0

By default JSFiddle wraps your code in a closure. This means that var name makes a local variable, and not a global one.

this, in the absence of explicit context, will default to window (at least, if strict mode is off it will). Variables will default to global, which become properties of window (again, if strict mode is off)

Coincidentally, they result in the same thing, and it works.

But the JSFiddle wrapping messes it up by making a local variable instead, so they no longer reference the same thing - in fact this is exactly why strict mode disables the behaviour - it's not reliable!

http://jsfiddle.net/rho3zyb4/1/ Updated fiddle showing the result with "no wrap" mode.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You get different results if you run this in the console versus in jsfiddle, that is because "this" in jsfiddle is a different object

jsFiddle output:

global:result
person1:Nicholas
person2:Greg

standard console output

"global:Michael"
"person1:Nicholas"
"person2:Greg"
leat
  • 1,418
  • 1
  • 15
  • 21
0

By passing this, you're passing "window" and in the case of jsfiddle the window's name is result.

If you run that in another window with a different name, the output will be different.

A. Rama
  • 903
  • 8
  • 18