语境

我有一个名为Entity的基类,并且UserGroup都从该对象派生;例如,如果实例化ID为12的用户,则下次尝试这样做时,它将返回相同的对象。我将它们存储在原型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)
}


您将获得具有不同原型的独特构造函数,但要避免重复。

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

10-13 08:23