Javascript 从父级中定义的继承类方法访问类变量

Javascript accessing class variable from an inherited class method defined in parent

本文关键字:继承 类方法 访问 类变量 定义 Javascript      更新时间:2023-09-26

嗯,我是原型编程/设计的新手。我很乐意提供帮助。

问题是为什么我在"查找"方法中的"this.__proto__instances"返回"未定义"?

如果我的方法错误,请原谅我,我会很高兴知道调用类方法以查找类变量数组中的元素的正确方法,而无需为每个孩子定义方法。

下面的代码中详细阐述了

这个问题。

谢谢。

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.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"); 

给出错误,指出它无法调用方法每个未定义。它可以调用方法查找,因此可以很好地继承。但是我猜查找方法定义中的">this._原型_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

如果要直接引用继承的方法,继承的意义何在?