What is the best way to make something like a class in JavaScript and create multiple instances of it?
I've tried the following:
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
It works if I use it to create one object, but when I create multiple objects and use any of them get following error:
Uncaught TypeError: undefined is not a function
What would cause this behaviour?
The issue is stateArray and currentState are private (local only to Test()
) So when you try to do stateArray.push
in this context stateArray
is undefined and therefore does not have a function called push. one way to fix this is make them a property of Test using the this
key word
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);
if you would like these to be private you could only return the publicly available functions from the constructor and keep the private data hidden
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.