如何在构造函数中访问构造函数成员?

时间:2016-06-22 23:29:12

标签: javascript angularjs

对不起,我不确定如何说出这个问题..我知道这是某种范围问题..但是我正在努力实现的目标不可能吗?

app.factory('SystemStatusConnectionFactory', ['$timeout', '$q', 'SystemStatusFactory', 'SystemStatusOptionsFactory',
function ($timeout, $q, SystemStatusFactory, SystemStatusOptionsFactory) {

    var self = this;

    var SystemStatusConnectionFactory = function (ip, user, pw, options) {
        this.data = {
            count: 0
        };

    this.PollIP = function () {
      console.log(this.data.count);  //WORKS
      $timeout(function () {
            console.log(self.data.count);  //DOES NOT WORK
            console.log(this.data.count);  //DOES NOT WORK
        }, 1000);
    }
   };
... etc

2 个答案:

答案 0 :(得分:1)

不确定您是否已经从评论中解决了这个问题(因为我不知道为什么它不应该首先起作用),但您是否尝试过使用AttackButton.OnClickObservable().Subscribe(_ => { Player.DoSomething(); //blabla }); 功能超时&#39的功能参数?这将消除使用bind()

的需要
var self = this

答案 1 :(得分:0)

如果没有看到更多代码,很难知道到底发生了什么。

如果你将它与你的函数绑定,你可以确保这指的是你想要的任何上下文。

app.factory('SystemStatusConnectionFactory', ['$timeout', '$q', 'SystemStatusFactory', 'SystemStatusOptionsFactory',
(function ($timeout, $q, SystemStatusFactory, SystemStatusOptionsFactory) {

    var self = this; //this is now pointing to 'app'

    var SystemStatusConnectionFactory = (function (ip, user, pw, options) {

        this.data = {  // this is now pointing to app as well.
            count: 0
        };

        this.PollIP = function () {
            $timeout(function () {
                console.log(self.data.count);  // Self points to app.
                console.log(this.data.count);  // This points to the window object
            }, 1000);
        }
    }).bind(this);
}).bind(app) // Use bind to set app as the context of the function or 'this'

**我假设你想要'this'来引用app **