我正在使用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;
    }
}});

===============>>#1 票数:1 已采纳

我发现了一个问题:

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

我删除了.prototype ,现在可以使用了。

  ask by qr11 translate from so

未解决问题?本站智能推荐: