0

The code is given below:

  function a() {
    function makeWorker() {
        this.ename = "Pete";
        return function() {
            console.log(this);
            console.log(this.ename);
        };
    }


    var work = makeWorker();
    work();
}
 var ename = "John";
a();

this.name outputs to "Pete".but i have defined another variable ename in the global scope.So why is "Pete" printing instead of "John"?.The program is running in non-strict mode.

Rahul Das
  • 13
  • 4

3 Answers3

2

makeWorker is kind of redundant here if a() is called without a this anyway, so let’s replace the call to makeWorker with what it does:

function a() {
    this.ename = "Pete";
    var work = function() {
        console.log(this);
        console.log(this.ename);
    };
    work();
}

var ename = "John";
a();

and replace the call to work with what it does:

function a() {
    this.ename = "Pete";
    console.log(this);
    console.log(this.ename);
}

var ename = "John";
a();

and replace the call to a with what it does, assuming again that this is the global object:

var ename = "John";
this.ename = "Pete";
console.log(this);
console.log(this.ename);

So you set the global ename to "John", then set it to "Pete", then print it and the result is "Pete". Nothing weird. It might help you to log something when each assignment happens in the original code:

function a() {
    function makeWorker() {
        console.log("Setting ename to Pete");
        this.ename = "Pete";
        return function() {
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}

console.log("Setting ename to John");
var ename = "John";
a();
Ry-
  • 218,210
  • 55
  • 464
  • 476
-1

It looks like you are executing the makeWorker and it is simple overriding the variable ename, and you are wanting to access a global variable.

Check out this article. How to access global variable in function hook in javascript?

TheRock
  • 24
  • 2
  • If all of the relevant details in your answer are provided in a link to another SO post, then this question should be closed as a duplicate of that post. You should flag it as such. – Ken White Jul 08 '17 at 03:31
-2

There are several different scopes, in JavaScript. The variable ename is created within the scope of the function. To access the global scoped variables you have to call them a different way.

https://www.w3schools.com/js/js_scope.asp

  • To access the variable at a global scope when you created a variable at the local function scope you have to call it using the window.{variableName}, in your case window.ename – Jason Mastnick Jul 08 '17 at 03:12
  • You should never have to post a comment to your own answer in order to add details. You always (regardless of reputation) have the ability to edit your own questions or answers. Please do so. – Ken White Jul 08 '17 at 03:27
  • This answer is just wrong. There is no `ename` variable in any function scope here. – melpomene Jul 08 '17 at 03:29