下面的代码不起作用,因为在函数被调用 this = window时。我期待 this = controller.actions.project,但后来了解了这个关键字的工作原理,现在明白为什么不是这样。
BROKEN
controller.actions = {
project: new TableauAction("Project",
function () {
$http.get('/reports/projects/').then(function (response) {
this.options = response.data;
});
}};
以下解决了这个问题,但它非常不优雅
WORKS
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;}
我的问题是,是否有更优雅的方法从函数中访问对象的属性,该函数被传递给它的构造函数?
答案 0 :(得分:1)
添加"这个"您的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;
});
}};
}