[英]Javascript: Accessing 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 member function of a class but getting an error: 我试图访问类的成员变量,该类是类的成员函数中的数组但是收到错误:
Can not read property
'length'
of undefined无法读取未定义的属性
'length'
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.
像integer这样的变量很容易访问,但大多数时候问题都在于数组。 Help would be appreciated.
帮助将不胜感激。
You need this
to make properties of the object in a constructor. 您需要
this
来在构造函数中创建对象的属性。
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. 然后一定要使用
new
来调用构造函数。
var ba = new BasicArgs();
ba.getByteStreamLength();
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;
}
Declaring var argData
doesn't create a property on the object. 声明
var argData
不会在对象上创建属性。 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. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.