Albert Orlando Albert Orlando - 6 months ago 7
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

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

Answer

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, this.foo 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("this.foo = " + this.foo);
  console.log("foo = " + foo);
  var foo = "test";
  console.log("foo' = " + foo);
  var vm = this;
  console.log("vm.foo = " + this.foo);
  vm.foo = myArg;
  console.log("vm.foo' = " + this.foo);
}

console.log("window.foo = " + window.foo);
console.log(">>> Test call 1");
myFunction("abc");

console.log("window.foo = " + window.foo);

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

console.log("window.foo = " + window.foo);

For convenience, here is the console output:

window.foo = undefined
>>> Test call 1
this.foo = undefined
foo = undefined
foo' = test
vm.foo = undefined
vm.foo' = abc
window.foo = abc
>>> Test call 2
this.foo = abc
foo = undefined
foo' = test
vm.foo = abc
vm.foo' = xyz
window.foo = xyz

As you can see, this inside the function actually refers to the global window object. That means that the value of vm.foo 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.