JavaScript 类扩展

标签 javascript oop inheritance extend

上下文

我有一个名为 Entity 的基类,UserGroup 均派生自该对象;例如,如果我实例化 ID 为 12 的用户,那么下次我尝试这样做时,它会返回相同的对象。我将它们存储在原型(prototype) items 变量中。为了将这些 item 变量分开,我必须单独声明 User 和 Group 函数,尽管它们包含相同的代码。

代码

Application.prototype.Entity = function() {

};

Application.prototype.Entity.prototype.print = function() {
    var container = $("<div class='user-tag'></div>");
    container.append("<a class='friend_list ellipsis_overflow' style='background-image:url(\"" + this.entity.pic.icon + "\");'"
        + "href ='user?id=" + this.entity.id + "'>" + this.entity.name + "</a>");

    return container;
};


//HOW TO GET RID OF THIS "REPETITION"
Application.prototype.User = function(entity) {
    this.entity = entity;
    this.entity.pic = this.entity.pic || Application.prototype.default.pic;
        if (this.items[this.entity.id]) {
        return this.items[this.entity.id];
    } else {
        this.items[this.entity.id] = this;
    }
};
Application.prototype.Group = function(entity) {
    this.entity = entity;
    this.entity.pic = this.entity.pic || Application.prototype.default.pic;
    if (this.items[this.entity.id]) {
        return this.items[this.entity.id];
    } else {
        this.items[this.entity.id] = this;
    }
};
// END REPEAT


Application.prototype.Group.prototype = new Application.prototype.Entity();
Application.prototype.User.prototype = new Application.prototype.Entity();

//Application.prototype.User.prototype.constructor = Application.prototype.Entity;
//Application.prototype.Group.prototype.constructor = Application.prototype.Entity; - these don't seem to work

//THESE items VARIABLES HAVE TO REMAIN SEPARATE
Application.prototype.Group.prototype.items = {};
Application.prototype.User.prototype.items = {};

问题

我特别想消除我的代码中的上述重复,但如果您看到任何其他不必要的代码,请发表评论。谢谢!

最佳答案

类似这样的吗?

function userAndGroupConstructor(entity) {
  this.entity = entity;
  this.entity.pic = this.entity.pic || Application.prototype.default.pic;
  if (this.items[this.entity.id]) {
    return this.items[this.entity.id];
  } else {
    this.items[this.entity.id] = this;
  }
}

Application.prototype.User = function() {
  return userAndGroupConstructor.apply(this, arguments)
}
Application.prototype.Group = function() {
  return userAndGroupConstructor.apply(this, arguments)
}

您可以获得具有不同原型(prototype)的不同构造函数,但避免重复。

关于JavaScript 类扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23723133/

相关文章:

javascript - 当 p 标签接近时向下移动元素

javascript - Firefox 中的 Websockets 不适用于多个 HTTPS 页面

java - 数据隐藏就是封装,但并不是所有的封装都是数据隐藏

java - 返回 unmodifiableList 是否可以接受,还是应该返回数组?

php - 将用户存储为对象是否有意义?

java - “every class in java extends the MetaClass Object” 是否意味着每个子类都会导致 Diamond 问题

javascript - 为什么 .not() 在这种情况下不起作用?

javascript - 在选择框/下拉列表中仅显示唯一值

java - 如何从其他类访问jFrame的组件?

c++ - 调用虚函数时继承类 "invalid pointer error"