[英]Javascript accessing class variable from an inherited class method defined in parent
好吧,我是原型编程/设计的新手。 我很乐意提供帮助。
问题是为什么我在“ find”方法中的“ this.__proto__instances
”返回“ undefined”?
如果我的方法不对,请原谅,我很高兴知道调用类方法以在类变量数组中查找元素的正确方法,而不必为每个孩子定义该方法。
下面的代码以注释的形式详细说明了该问题。
谢谢。
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,因此可以很好地继承。 但是,我猜找到方法定义中的“ this._ proto _instances”是错误的。
编辑:
Attribute.prototype.pushInstance=function(my_attribute){
this.__proto__.instances.push(my_attribute);
};
此功能有效。 尽管实例数组由ActiveAttribute或ReferenceAttribute拥有,而不是Attribute本身拥有,但是此函数确实可以将其推入数组。
这是因为您正在执行此操作:
var ref_attr=ReferenceAttribute.prototype.find("a uid");
ReferenceAttribute.prototype
对象是从Attribute
构造函数创建的实例,而Attribute.prototype
没有.instances
属性,也没有直接在该对象上定义.instances
属性。
user2736012有您的答案,所以只提供一条评论:
并非所有使用的浏览器都标准化或支持__proto__
属性,因此请不要使用它。 此外,如果要访问对象的[[Prototype]]
属性,请使用标准属性解析:
this.instances
如果要直接引用继承的方法,继承的意义是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.