Javascript类扩展

时间:2014-05-18 14:41:34

标签: javascript oop inheritance extend

CONTEXT

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

CODE

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 = {};

问题

我特别想摆脱上面提到的重复代码,但是如果你看到任何其他不必要的代码,请发表评论。谢谢!

2 个答案:

答案 0 :(得分:1)

这样的东西?

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)
}

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

答案 1 :(得分:0)

你可以这样做:

Application.prototype.Group = Application.prototype.User;

由于Application.prototype.User包含函数引用,您只需将其指定给Application.prototype.Group