Exploring scopes in JavaScript has led me to an interesting discovery when calling functions from an array. In the example below, I experiment with three different scopes: one bound to an Object named foobar, one bound to window, and a third one which points back to the function itself. I'm intrigued by why the function is scoped to itself rather than the global window object. Could this be due to Array access being a function call itself, causing the stored function to exist in a local scope?
var foobar = {
doWork: function() {
console.log('doing some work...');
console.log(this);
}
}
foobar.doWork(); // `this` will refer to foobar
var doWorkClone = foobar.doWork;
doWorkClone(); // `this` will refer to window
var workClones = [];
workClones.push(foobar.doWork);
workClones[0](); // `this` will refer to the doWork function itself