gpt4 book ai didi

JavaScript 类扩展

转载 作者:行者123 更新时间:2023-12-03 12:36:18 25 4
gpt4 key购买 nike

上下文

我有一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com