从传递给它的构造函数的函数访问 javascript 对象的属性

Access properties of javascript object from a function which is passed into it's constructor

下面的代码不起作用,因为当时函数被调用 this=window。我原以为 this = controller.actions.project 但后来更多地了解了 this 关键字的工作原理,现在明白为什么不是这样了。

损坏

controller.actions = {
        project: new TableauAction("Project",
            function () {
                $http.get('/reports/projects/').then(function (response) {
                     this.options = response.data;
                });
            }};

下面解决了问题,但是比较不优雅

作品

 controller.actions = {
        project: new TableauAction("Project",
            function () {
                var self = controller.actions.project;
                $http.get('/reports/projects/').then(function (response) {
                     self.options = response.data;
                });
            }};

TableauAction 对象:

function TableauAction(name, onChange) {
this.name = name;
this.onChange = onChange;}

我的问题是是否有更优雅的方法从传递给构造函数的函数访问对象的属性?

将 "this" 上下文添加到您的 onChange 回调中。

function TableauAction(name, onChange) {
  this.name = name;
  this.onChange = onChange;
  //add this context to your onChange
  this.onChange.bind(this);
}

然后将以下内容更改为:

controller.actions = {
        project: new TableauAction("Project",
            function () {
                //"this" refers to TableauAction instance now
                var $this = this;
                $http.get('/reports/projects/').then(function (response) {
                     //this refers to $http callback response..
                     $this.options = response.data;
                });
            }};
}