4

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

Can not read property 'length' of undefined

Class:

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 of the example but i have come across this at many places. variables like integer are easily accessible but most of the times problem is with arrays. Help would be appreciated.

3 Answers 3

3

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

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

There's no way for prototyped functions to directly access the variable scope of the constructor function.

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

var ba = new BasicArgs();

ba.getByteStreamLength();
Sign up to request clarification or add additional context in comments.

Comments

0

You can access private variable of function

modified code:

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

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

Comments

0

Declaring var argData doesn't create a property on the object. It just creates a local variable that goes away as soon as the constructor exits. You need to do

this.argData = new Uint32Array(1)

instead.

1 Comment

Not exactly correct. The variable will still exist, but it isn't accessible outside of the scope of the constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.