/**
* adds an entry to the list
*
* @param data {Object}
* @return this
*/
ElementList.prototype.addEntry = function(data){
if (!data) return this;
data['type'] = this.children_type;
// add the entry to the current elements
this.element_list.push(new FavoriteEntry(data));
this.refresh();
return this;
};
/**
* favorites extend ElementList
*
* @param setting_list
* @constructor
*/
function FavoriteList(setting_list){
ElementList.call(this, setting_list);
}
FavoriteList.prototype = new ElementList();
FavoriteList.constructor = FavoriteList;
这是我的一个教育项目的简短代码片段。 我想做的是减少重复代码,所以我创建了一个通用的 ElementList 对象 所以
- 示例FavoriteList继承父对象原型(prototype)
- 构造函数指向子对象
- 父级构造函数在子级中调用。
效果很好,我的问题是
// add the entry to the current elements
this.element_list.push(new FavoriteEntry(data));
这应该创建一个基于子对象的新实例,因此我需要获取调用父方法的子实例的名称
我试过了 - this.constructor(指向父级) - this.构造函数.name - 这个FavoriteList实例(有效)
因为我不想传递名称,并且我认为迭代instanceof“选项”并不是很明智。
我想了解一些如何访问父元素方法主体中的子实例名称的见解。
拜托,我只需要一个明确的答案!我已经阅读了解决方法!如果不可能,就这么说:)
提前谢谢:)
最佳答案
this.element_list.push(new FavoriteEntry(data));
This should create a new instance of an Object BASED on the CHILD so therefore I need to get the name of the child instance that's calling the parent method
不,你似乎不需要知道这个名字。您所需要的只是一个帮助函数来生成新的 Entry
实例,可以覆盖该实例以生成更具体的条目。也许您已经通过使用 data
传递 children_type
来做到这一点...
i tried - this.constructor (point to the parent)
如果您正确设置了构造函数
,它应该可以工作。将代码更改为
FavoriteList.prototype.constructor = FavoriteList;
// ^^^^^^^^^^
此外,您可能想要use Object.create
instead of new
设置原型(prototype)链。
关于Javascript对象继承如何获取Child实例名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21115297/