我必须弄清楚如何正确开发oop-javascript。我阅读了很多有关prototypes
的内容,但互联网向我解释说,如果我多次创建对象,则只需要它。但是我的SuperInterface
仅存在一次。因此,我将其创建为对象:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: this.superaction
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
运行
init()
可将title
成功放入控制台。但是永远不会发出警报。我不明白,为什么不呢?我应该改变什么? 最佳答案
该对象初始化程序中间的this
的值是,而不是对“正在构造”的对象的引用。由于该对象尚不存在,因此无法在初始化期间获取此类引用,也无法使用this
对其进行引用。因此,您真的不能初始化这样的属性。但是,您可以将其拆分为单独的语句:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: null;
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;