我必须弄明白,如何以正确的方式开发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();
Run Code Online (Sandbox Code Playgroud)
运行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;
Run Code Online (Sandbox Code Playgroud)