【发布时间】:2013-10-11 02:49:34
【问题描述】:
嗯,我是原型编程/设计的新手。 我很乐意为您提供帮助。
问题是为什么我在“find”方法中的“this.__proto__instances”返回“undefined”?
如果我的方法是错误的,请原谅我,我很高兴知道调用类方法以在类变量数组中查找元素的正确方法,而无需为每个孩子定义方法。
详细问题在下面的代码中作为 cmets 进行了阐述。
谢谢。
function Attribute(name,type){
//some members definition, including uid, name, and type
};
Attribute.prototype.find=function(uid){
var found_attr=false;
this.__proto__.instances.forEach(function(attr){
if (attr.uid == uid) found_attr=attr;
});
return found_attr;
};
this.__proto__.instances.forEach(function(attr){ 上面是错误的行。日志说“无法为未定义的每个调用方法”
function ReferenceAttribute(arg_hash){
Attribute.call(this,arg_hash.name,arg_hash.type);
//some members definition
this.pushInstance(this);
};
this.pushInstance(this); 将此实例推送到正常工作的 ReferenceAttribute.prototype.instances
ReferenceAttribute.prototype=new Attribute();
ReferenceAttribute 通过原型链方法继承 Attribute
ReferenceAttribute.prototype.instances=new Array();
上面的行声明了包含所有引用属性实例的数组。 对于 ReferenceAttribute 的每个新对象,它将被推送到这个数组中,在方法 pushInstance() 中完成。 推送总是成功的,我通过控制台日志检查了它们。该数组确实包含 ReferenceAtribute 实例
function ActiveAttribute(arg_hash){
Attribute.call(this,arg_hash.name,arg_hash.type);
//some members definition
this.pushInstance(this);
};
ActiveAttribute.prototype=new Attribute();
ActiveAttribute.prototype.instances=new Array();
在程序中使用它
var ref_attr=ReferenceAttribute.prototype.find("a uid");
给出的错误是它不能调用未定义的 forEach 方法。 它可以调用方法find,因此可以很好地继承。但是我猜find方法定义中的“this._proto_instances”是错误的。
编辑:
Attribute.prototype.pushInstance=function(my_attribute){
this.__proto__.instances.push(my_attribute);
};
此功能有效。虽然实例数组由 ActiveAttribute 或 ReferenceAttribute 拥有,而不是 Attribute 本身,但此函数确实可以将其推送到数组。
【问题讨论】:
-
谢谢。我会做一些编辑
标签: javascript oop prototype