Albert Orlando Albert Orlando - 4 months ago 5x
AngularJS Question

JavaScript: Scope of 'this' within a function

I'm somewhat new to JavaScript and have a few questions about scope that don't seem to have been explicitly asked about before. At the top of a function I'm working on in angular a variable

is set equal to
. I understand that anything prefaced with
going forward will be in scope of
however how is this different from being in the function's scope to begin with? To be more explicit, how would = "test"
differ from
var foo = "test"
inside of a function in terms of its scope. Any help would be much appreciated.


If you set vm = this, then properties of vm can persist beyond the scope of the current function invocation. In contrast, a local variable value (e.g., var foo = "test") does not persist past the current function invocation.

Basically, within a function is not equivalent to var foo within that same function. The first actually references a property value on the this object, whereas the second only references a local variable in the current function invocation scope.

Here's an example to illustrate this difference:

function myFunction(myArg) {
  console.log(" = " +;
  console.log("foo = " + foo);
  var foo = "test";
  console.log("foo' = " + foo);
  var vm = this;
  console.log(" = " +; = myArg;
  console.log("' = " +;

console.log(" = " +;
console.log(">>> Test call 1");

console.log(" = " +;

console.log(">>> Test call 2");

console.log(" = " +;

For convenience, here is the console output: = undefined
>>> Test call 1 = undefined
foo = undefined
foo' = test = undefined' = abc = abc
>>> Test call 2 = abc
foo = undefined
foo' = test = abc' = xyz = xyz

As you can see, this inside the function actually refers to the global window object. That means that the value of that you assign inside the function is actually available anywhere that window is accessible (i.e., everywhere in your script). You can change what object is used as this if you invoke the function using its call method, and explicitly pass a different object as thisArg.