I'm playing around with scopes in JavaScript and I was curious about something I ran across when calling a function from an array. In the below example I work with three different scopes. One bound to an Object called foobar, one bound to window and then a third one which actually refers to the function itself. I'm just curious why the function is scoped to itself and not to the global window object. Is it because Array access is a function call itself so the stored function is 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
thishas nothing to do with scopethisis determined upon each function call based on the situation.thiswill refer to the doWork function itself" — No, it won't. Note the[and]in the output. It refers toworkClones.bindreturns calls the original function with a predefinedthis- but neither of the two functions have athisvalue bound, technically.