我正在尝试以面向对象的方式在Javascript中实现模型。假设我的对象X具有一堆函数。我想有一个对象数组“在X中”,它的某些字段指向X中的某些函数。这是我尝试过的示例:
function X(){
this.open = function(e){...};
this.run = function(e){...};
this.close = function(e){...};
//...
this.STATES = {
1: {name : "opening", applyAction : this.open},
2: {name : "runing", applyAction : this.run},
3: {name : "closing", applyAction : this.close},
//...
};
this.currentState = this.STATES[1];
//...
this.update = function(e){
//...
currentState.applyAction(e);
//...
}
但是这种方法无法按预期工作。我无法弄清楚哪里出了问题,如果您有另一种做同一件事的方式,我将不胜感激。
这不起作用,因为以下代码中的“ this”指向您正在定义的文字对象,而不是预期的“ this”:
this.STATES = {
1: {name : "opening", applyAction : this.open},
2: {name : "runing", applyAction : this.run},
3: {name : "closing", applyAction : this.close},
//...
};
尝试
function X() {
var self = this;
this.open = function() {
// ...
}
this.STATES = {
1: {name: "opening", applyAction: self.open},
...
我还将阅读有关Javascript范围的信息。