gpt4 book ai didi

使用 underscore.js 的 Javascript 继承

转载 作者:行者123 更新时间:2023-12-03 10:07:58 24 4
gpt4 key购买 nike

我使用underscore.js _.create函数来实现继承,但是当我尝试使用ListMakerTask_2时:

ListMakerTask_2.initialize("div1", phones);
ListMakerTask_2.RenderList();

它给了我:

TypeError: ListMakerTask_2.initialize is not a function

但是当我使用 ListMakerTask_1 时它工作正常:

ListMakerTask_1.initialize("div1", phones);
ListMakerTask_1.RenderList();

类层次结构:

  var Abstract_ListMaker = {
divID: null,
arr: null,
//Empty abstract function
initialize: function(){},
//Empty abstract function
RenderList: function(){}
};
var ListMakerTask_1 = _.create(Abstract_ListMaker.prototype,{
initialize: function(divID, arr){
this.divID = divID;
this.arr = arr;
},
RenderList: function(){
var out = "<ul>";
for(var i = 0; i < this.arr.length;i++){
out+="<li>" + this.arr[i].age +"<br>" + this.arr[i].id +"<br><img src='" + this.arr[i].imageUrl +"'/><br>" + this.arr[i].name + "<br>" + this.arr[i].snippet + "</li>";
}
out+= "</ul>";
document.getElementById(this.divID).innerHTML = out;
}});
var ListMakerTask_2 = _.create(ListMakerTask_1.prototype, {RenderList: function(){
var createNewUL = document.createElement("ul");
createNewUL.id = "phoneList";
document.getElementById(this.divID).appendChild(createNewUL);
for(var i = 0; i < this.arr.length;i++) {

var chunk = "<li>" + this.arr[i].age + "<br>" + this.arr[i].id + "<br><img src='"
+ this.arr[i].imageUrl + "'/><br>" + this.arr[i].name + "<br>" + this.arr[i].snippet + "</li>";

document.getElementById("phoneList").innerHTML += chunk;
}
}});

最佳答案

我发现一个问题:

var ListMakerTask_2 =_.create(ListMakerTask_1.prototype,...);

我已经删除了 .prototype,现在它可以工作了。

关于使用 underscore.js 的 Javascript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278729/

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