Javascript对象继承如何获取Child实例名称

标签 javascript oop

/**
 * 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/

相关文章:

javascript - 当一个文件超过 20000 行时,您使用哪种编辑器或 IDE?

javascript - 查找两个日期之间的月份名称和年份

javascript - 对象的属性更改时会激活功能吗?

c++ - 使用线程执行任务并稍后执行某些操作的模式

javascript - 什么时候可以使用.then来使用当前返回的值?

javascript - 具有 PNG 后备功能的 Google map SVG 标记

javascript - 我不了解Crockford的JavaScript:前进的道路

java - 如何重构内部类MouseAdapter?

java - 为什么我们不能在Java中实例化一个抽象类?

关于 count_if : expected primary-expression before 的 C++ 错误