在JavaScript中创建类似于类的内容并创建多个实例的最佳方法是什么?
我尝试了以下内容:
function Test() {
var currentState = -1;
var stateArray = new Array();
}
Test.prototype.SetState = function(state) {
this.currentState = state;
stateArray.push(state);
if (stateArray.length > 2) {
stateArray.splice(0, 1);
}
}
Test.prototype.GetState = function() {
return this.currentState;
}
var Object1 = new Test();
var Object2 = new Test();
var EState = {
ONE: 1,
TWO: 2,
};
Object1.SetState(EState.ONE); //<< fails here
如果我使用它创建一个对象,它会起作用,但是当我创建多个对象并使用其中任何一个时,会出现以下错误:
Uncaught TypeError: undefined is not a function
什么会导致这种行为?
答案 0 :(得分:2)
问题是stateArray和currentState是私有的(只有Test()
本地)所以当你在这个上下文中尝试stateArray.push
时,stateArray
是未定义的,因此没有调用的函数推。解决这个问题的一种方法是使用this
关键字
function Test() {
this.currentState = -1;
this.stateArray = new Array();
}
Test.prototype.SetState = function(state) {
this.currentState = state;
this.stateArray.push(state);
if (this.stateArray.length > 2) {
this.stateArray.splice(0, 1);
}
}
Test.prototype.GetState = function() {
return this.currentState;
}
var Object1 = new Test();
var Object2 = new Test();
var EState = {
ONE: 1,
TWO: 2,
};
Object1.SetState(EState.ONE);
console.log(Object1);
如果您希望这些是私有的,您只能从构造函数返回公开可用的函数并隐藏私有数据
function Test() {
//private
var currentState = -1;
var stateArray = new Array();
//public
return {
SetState: function(state) {
currentState = state;
stateArray.push(state);
if (stateArray.length > 2) {
stateArray.splice(0, 1);
}
},
GetState: function() {
return currentState;
}
}
}
var Object1 = new Test();
var Object2 = new Test();
var EState = {
ONE: 1,
TWO: 2,
};
Object1.SetState(EState.ONE);
Object2.SetState(EState.TWO);
console.log(Object1.GetState());
console.log(Object2.GetState());