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();