javascript THIS与angular $ SCOPE。$ ON

时间:2017-03-15 22:02:45

标签: angularjs virtual-machine this

我已经使用角度1.x工作了2年左右。我经常按照食谱不经常惹麻烦。最近我开始尝试新的方法,以便更好地理解角度和javascript。

我曾经相信我在javascript控制器中声明的“vm”是在html中声明的data-ng-controller =“mycontroller as vm”的链接(绑定)。我刚学会了我可以用不同的方式命名它们,并且绑定仍然会完美地发生。

然后,我决定停止在控制器中声明“vm”的东西并开始使用本机javascript“this”限定符。

我尝试了以下内容:

angular.module('app')
    .controller('Customers', [function() {
 //   var vm = this;
      this.title = 'Customers';
      this.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];


    function 1stFunction () {
        this.obj1 = {}; 
    ;



    function 2ndFunction () {
        this.var2 = {};     
    ;


    $scope.$on('myListener', function() {
        this.var3 = {};
    });

    }]);

令我惊讶的是,当我运行应用程序时,我得到一条“这是未定义的”消息(或接近此内容的消息),指的是 $里面的 this.var3 = {} 范围。$上即可。只是 $ scope。$ on 中的归因。函数内的所有其他属性都可以工作。

如果我只是在整个控制器上替换“this”“for”vm“,那么事情会再次完美。

我想知道是否有人可以解释到底发生了什么。

感谢。

1 个答案:

答案 0 :(得分:2)

传递给$ scope的匿名函数。$ on()只是一个常规函数。它不受this的约束。您需要使用

 $scope.$on('myListener', function() {
    this.var3 = {};
 }.bind(this));

或使用自动执行此操作的ES6箭头功能(如果您的浏览器支持ES6,或者您将代码从ES6转换为ES5):

$scope.$on('myListener', () => {
  this.var3 = {};
});

或者,正如您迄今为止所做的那样,在所有函数捕获的局部变量中捕获this的值:

var vm = this;

// no risk of not binding this anymore
$scope.$on('myListener', function() {
    vm.var3 = {};
});

坦率地说,如果你还没有准备好使用ES6,我会继续使用vm别名技巧(或者使用$ scope,它没有这个问题)。