I was trying to understand the closure but I was not getting how it can access the variable of a function that no longer exists. So I wrote this.
function foo() {
var from = 'from node';
function func() {
console.log('hello world', from);
}
func();
}
foo();
Output
node index.js
hello world from node
OK this is also working
Now what if I move the func to global scope
function func() {
console.log('hello world', from);
}
function foo() {
var from = 'from node';
func();
}
foo();
And it didn't work as I thought. What if I bind the this and then call Like this
function func() {
console.log('hello world', this.from);
}
function foo() {
var from = 'from node';
func.bind(this)();
}
foo();
According to me, this should work as I have explicitly given it this variable.
But it is still printing undefined which don't understand why.