【问题标题】:Access private variables in declared function访问声明函数中的私有变量
【发布时间】:2015-04-13 12:54:41
【问题描述】:

嗨,我一直在尝试打字稿,到目前为止一切看起来都不错,但我似乎无法弄清楚什么。我正在使用 angular,所以我将在它的上下文中提出我的问题。

这是我的代码:

class PersonCtrl{
    private $scope: IPersonScope;
    private $http: ng.IHttpService;

    static $inject = ['$scope', '$http']
    constructor($scope: IPersonScope, $http: ng.IHttpService) {
        this.$scope = $scope;
        this.$http = $http;
        this.init();
    }

    init() : void  {
        this.$scope.fullName = 'Justin S.';
        this.$scope.buttonClick = this.buttonClick;

        console.log("-----------------Init------------------");
        console.log(this);
    }

    buttonClick(): void {
        console.log("-----------------ButtonClick------------------");
        console.log(this.$http);
    }


}

我想要实现的是当我单击一个按钮时能够访问 $http 服务。buttonClick 函数绑定在视图上,我省略了 html 代码,因为我认为没有必要。

当我单击按钮时,我希望能够对服务器进行 ajax 调用,但问题是“this”将引用 javascript 中按钮的上下文而不是 PersonCtrl 的上下文,因此我无法访问任何我声明为私有的变量。

我知道我所采用的方法可能不是我今天早上开始学习打字稿的最佳方式,所以如果有任何可以改进的地方,请告诉我

如何在buttonClick函数中访问$scope和$http?

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    变化:

    this.$scope.buttonClick = this.buttonClick;
    

    收件人:

    this.$scope.buttonClick = () => this.buttonClick();
    

    这将生成以下保留 this 的 JavaScript:

    var _this = this;
    this.$scope.buttonClick = function() { return _this.buttonClick(); };
    

    【讨论】:

      【解决方案2】:

      buttonClick 中的this 并不是您最初期望的那样。它不是控制器,而是方法自己的范围。

      因此,您需要创建对 this 的引用 - 因为我对 TypeScript 不太熟悉(在 CoffeeScript 中您可以只使用粗箭头),所以我会使用常规的 JavaScript 方法:

      private $scope: IPersonScope;
      private $http: ng.IHttpService;
      // declare var for reference of this
      var _this;
      
      init() : void  {
        // save the reference for use in other methods
        _this = this;
        // ...
      }
      
      buttonClick(): void {
        console.log("-----------------ButtonClick------------------");
        // use the reference to the controller's `this`
        console.log(_this.$http);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多