我试图以面向对象的方式在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);
//...
}
但是这种方法不能按预期工作。我无法弄清楚出了什么问题,如果你有另外一种做同样事情的方式,我会非常感激。
答案 0 :(得分:1)
这不起作用,因为以下代码中的'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范围的内容。