在将数组插入数组后,我遇到了使用类方法的问题。当我把它拉回来时,我再也无法使用它了。
假设我有以下内容:
// a simple atomic class
function raw_msg(msg) {
this.msg = msg;
this.print = function () {
console.log(this.msg);
}
}
// and then i have this container for this "atomic" class
// which accept array of unknown object (known to me though..) = in_buffer
// i.e in_buffer is just an array of objects (one type of object)
function buffer(in_buffer) {
this.trans_buffer = null;
if (in_buffer!=null)
this.set_buffer (in_buffer);
this.set_buffer = function (buffer) {
this.trans_buffer = [];
var length = buffer.length,
row, new_raw_msg;
for(var x = 0; x < length; x++) {
row = buffer[x];
this.trans_buffer.push(new raw_msg(row));
}
console.log(this.trans_buffer);
}
this.use_some_raw_msg_method = function () {
var firstrow = this.trans_buffer[0];
firstrow.print(); // here is the problem!!!
//this here where i need help as it yield the error:
//Uncaught TypeError: Object #<Object> has no method 'print'
}
}
// this is how i use it, this code sits in a diffrent yet another class...
// this here im just building fake array
var buffer_in = [];
for (var x=0;x<10;x++)
buffer_in.push ("whatever" + x);
this.trans_buffer = new trans_helper(buffer_in);
this.trans_buffer.use_some_raw_msg_method (); // will yield the error as described
我希望这一点很清楚,如果你需要澄清,请随时提出。
感谢您的帮助!
答案 0 :(得分:1)
您的代码遇到了一些问题。
关联数组没有.push()
方法,因此以下行失败:
buffer_in.push ("whatever" + x);
要解决此问题,只需声明plain array:
var buffer_in = [];
您尝试创建一个名为 trans_helper 的函数实例,该实例不存在。名称是 buffer ,因此修复将是:
var trans_buffer = new buffer(buffer_in);
最后但并非最不重要的是,当它仍然不存在时,你试图在“类”中调用函数。 JavaScript不会提前“编译”函数,当内部函数它将逐行进行时。所以在代码的这一行:
this.set_buffer (in_buffer);
在你的班级中仍然没有名为“set_buffer”的功能。要解决此问题,请将上面的函数声明置于顶部。