Javascript: access to a member variable (array) of a class in member functions

I am trying to access a member variable of a class, which is an array in a member function of a class, but gets an error:

Unable to read property 'length' from undefined

Grade:

 function BasicArgs(){ var argDataType = new Uint8Array(1); var argData = new Uint32Array(1); } 

Member function:

 BasicArgs.prototype.getByteStreamLength = function(){ alert(this.argData.length); return i; } 

This is one example, but I have come across this in many places. integer variables are easily accessible, but in most cases the problem is with arrays. Help will be appreciated.

+4
source share
3 answers

You need this to make the properties of the object in the constructor.

 function BasicArgs(){ this.argDataType = new Uint8Array(1); this.argData = new Uint32Array(1); } 

There is no way to prototype functions for direct access to the variable area of ​​a constructor function.

And then be sure to use new to invoke the constructor.

 var ba = new BasicArgs(); ba.getByteStreamLength(); 
+3
source

You can access a private function variable

modified code:

  function BasicArgs(){ this.argDataType = new Uint8Array(1); this.argData = new Uint32Array(1); } BasicArgs.prototype.getByteStreamLength = function(){ alert(this.argData.length); return i; } 
0
source

The var argData does not create an object property. It simply creates a local variable that leaves as soon as the constructor exits. You need to do

this.argData = new Uint32Array(1)

instead.

0
source

Source: https://habr.com/ru/post/1440566/


All Articles