1

I am adapting a controller to the "controller as" syntax. But while transforming the code, I remarked that I can't access the "scope" variables with this out of a function. If I understand the concept of this, then this does access the object it is used in. As example this code:

this.scopeVariable = undefined;

this.fooFunction = function () {
            resource.get()
                .$promise.then(function (result) {
                this.scopeVariable = result.foo;
            });
        };

So when I try to set the scopeVariable with this, I actually try to access an object from fooFunction, right? If this is the case, how can I grab an object outside of the function within the function?

Thanks for your answers!

Shinjitaku
  • 31
  • 7

2 Answers2

1

You have this problem because the this keyword changes definition when in a different scope. That means that if you have a simple object e.g.

var a = {
    b: function() {
        console.log(this); // => will log the value of "a"
        setTimeout(function() {
            console.log('just some rubbish');
            console.log(this); // => will log inner function scope instead of "a"
        }, 200)
    }
} 

a.b(); // to see the results

To prevent this issue from happening you can reassign this to a variable which will stay intact through deeper scopes like this:

this.scopeVariable = undefined;
var self = this;

this.fooFunction = function () {
  resource.get()
  .$promise.then(function (result) {
    // using self. instead of this. makes the difference here
    self.scopeVariable = result.foo;
  });
};
SidOfc
  • 4,552
  • 3
  • 27
  • 50
mildog8
  • 2,030
  • 2
  • 22
  • 36
0

Capturing the this being the scope in a variable: var that = this:

var that = this;
this.fooFunction = function () {
            resource.get()
                .$promise.then(function (result) {
                that.scopeVariable = result.foo;
            });
        };
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206