class - Objects & Methods in JavaScript -


What is the best way to create something like JavaScript in a javascript and make many examples of it?

I have tried the following:

  function test () {var currentState = -1; Var states = New Array (); } Test.prototype.SetState = function (state) {this.currentState = state; StateArray.push (state); If (statearelineline; gt; 2) {stateArray.splice (0, 1); }} Test.prototype.GetState = function () {return this.currentState; } Var object 1 = new test (); Var object 2 = new test (); Var Estate = {One: 1, 2: 2,}; Object1.SetState (EState.ONE); // & lt; & Lt; Here fails  

This works if I use it to create an object, but when I make more than one object and any of them receive the following error :

  Uncaught TypeError: Undefined is not a function  

What would be the reason for this behavior?

This issue is state and current status is private (only local test () ) So when you try to do stateArray.push in this context, stateArray is undefined and therefore there is no function called push, one way to fix it is to Use 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 & gt; 2) {this.stateArray.splice (0, 1);}} Test.prototype.GetState = function () {return this.currentState;} Var object1 = new test (); Var object 2 = new test (); var estates = {a: 1, 2: 2;} Object1.SetState (EState.ONE); Console.log (object1);  

If you want If it is private then you can only fire the function available from the constructor Hide and hide private data

  Function Test () {// Private var currentState = -1; Var StateAre = new Array (); // Public Return {Settet: Function (State } {CurrentState = state; StateArray.push (state); If (statearelineline; gt; 2) {stateArray.splice (0, 1); }}, Gatestate: function () {return the current status; }}} Var Object 1 = New Test (); Var object 2 = new test (); Var Estate = {One: 1, 2: 2,}; Object1.SetState (EState.ONE); Object2.SetState (EState.TWO); Console.log (Object1.GetState ()); Console.log (Object2.GetState ());  


Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -