1

I have read through call() method and wondering on the global output below. Shouldnt it be this.name where in this case "Michael". However the output displayed is undefined.

---NEW INFORMATION : THIS IS RUNNING THROUGH NODEJS---

function sayNameForAll(label) {
console.log(label + ":" + this.name);
 }

var person1 = {
name: "Nicholas"
};

var person2 = {
name: "Greg"
};

var name = "Michael";

sayNameForAll.call(this,"global");  //ouput global:undefined
sayNameForAll.call(person1,"PersonName1"); //PersonName1:Nicholas
sayNameForAll.call(person2,"PersonName2"); //PersonName2:Greg
2
  • 1
    How do you call this code? Are you sure you're in a global scope? It works as expected: jsfiddle.net/7pxsh8gh Commented Mar 10, 2015 at 8:26
  • your code works fine for me. Commented Mar 10, 2015 at 8:26

2 Answers 2

2

The reason is probably that in this context, this is not the same scope. This can happen because of several reasons:

  • You're running this in a function (even a (function() { self invoking function })())
  • You're running this in nodejs and not in the browser, in node, in the global scope, this is undefined as opposed to window in the browser.
Sign up to request clarification or add additional context in comments.

2 Comments

@zerkms Because in the global scope in node, this is undefined as opposed to window in the browser.
oh yes i am running on nodejs...How could this explain
0

Works fine here (click Run Snippet).

Is your code running inside another function? If it is, then the variables you declare would not be on the global object and depending on how you are invoking the function, this might not refer to the global object.

function sayNameForAll(label) {
    console.log(label + ":" + this.name);
}

var person1 = {
    name: "Nicholas"
};

var person2 = {
    name: "Greg"
};

var name = "Michael";

sayNameForAll.call(this,"global");  //ouput global:undefined
sayNameForAll.call(person1,"PersonName1"); //PersonName1:Nicholas
sayNameForAll.call(person2,"PersonName2"); //PersonName2:Greg

1 Comment

Because in the global scope in node, this is undefined as opposed to window in the browser. – Second Rikudo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.