Javascript 从父级中定义的继承类方法访问类变量
Javascript accessing class variable from an inherited class method defined in parent
嗯,我是原型编程/设计的新手。我很乐意提供帮助。
问题是为什么我在"查找"方法中的"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
如果要直接引用继承的方法,继承的意义何在?
- 使构造函数参数具有ES6类方法的特权
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- Javascript中的类方法
- 在 Array.map() 中调用类方法
- 从类方法中的 ajax post 函数回调函数更改 javascript 类属性
- 类方法中的上下文作为变量
- 如何将类方法设置为等于多个函数?-Javascript
- 将类方法绑定到类外绑定的事件处理程序内的AJAX成功回调
- Node.JS:类方法作为回调
- 如何从将在html页面中使用的java脚本中调用java类方法
- 在类方法中使用React.js静态
- 在不使用@syntax的情况下修饰ES6类方法
- 如何使用jQuery通过ajax调用php类方法,但不需要任何php处理程序文件
- 从常规ES6类方法中调用静态方法
- 访问父“;这个“;变量,来自继承类
- 在Javascript中,如何继承和扩展正在继承的方法
- Javascript 从父级中定义的继承类方法访问类变量
- 从其他类继承原型方法,而不重写自己的原型方法
- 如何使用继承类的方法
- 如何在CoffeeScript或Javascript中列出继承类的方法