简体   繁体   中英

AngularJS: What is 'this' when AngularJS controller is a member function of a class?

I use a member function of a class to be AngularJS controller: Note: the code below is compiled from some TypeScript code.

function Clazz(x) {

   this.Member = x;

   this.Func= function ($scope) {          
      $scope.message = '' + this.Member;   // this.Member is undefined
   }
} 


app.controller('TaxCtrl',  new Clazz('Hello').Func  );

The Func is called when the I switch to the TaxCtrl , but the this seems not to be the instance of Clazz because this.Member is always undefined.

When Func is a member of the Clazz instance then this will work. When angular constructs the function as an object is is creating a new object where this is referencing the instance of Func .

Here is a jsbin example:

http://jsbin.com/rocopiwila/edit?js,console

If you are trying to share properties down to controllers use services and injectables instead.

Try this:

function Clazz(x) {

   this.Member = x;
   self = this;

   this.Func= function ($scope) {          
      $scope.message = '' + self.Member;   
   }
} 


app.controller('TaxCtrl',  new Clazz('Hello').Func  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM