Javascript原型函数,记住延迟加载的最后一个值

时间:2014-02-23 00:21:26

标签: javascript jquery performance prototype

我目前正在开发一个webapp,我不得不担心潜在的大型数组。这些数组包含许多id,将添加到html列表中。因此,给定一个170个ID的数组,我将得到一个ul,它包含170个li元素。由于我不必担心搜索,但性能我决定使用延迟加载。到目前为止,我正在加载大数组,现在正在编写一个函数,根据用户位置添加新元素。

此函数需要记住它的最后位置,以防它没有获得特定的新数字(第二个参数设置)。我试图在函数属性的帮助下实现这一点。这是我到目前为止(ids是数组,pos可以设置的位置):

Player.prototype.showPlaylist = function (ids, pos) {
    //In case pos isn't set, use your old value
    showPlaylist.pos = pos !== "undefined" ? showPlaylist.pos : showPlaylist.pos;
    console.log(showPlaylist.pos);
    for (var i = showPlaylist.pos; i < ids.length; i++) {
        //create new html elements
    }
}

不幸的是我得到了

  

showPlaylist未定义

在console.log()上。这是我第一次使用延迟加载和具有内存的函数,因此可能有更好的解决方案(我真的应该避免使用全局变量)。

2 个答案:

答案 0 :(得分:2)

Player.prototype.showPlaylist = function (ids, pos) {
    //In case pos isn't set, use your old value
    this.pos = pos !== "undefined" ? this.pos : pos;
    console.log(this.pos);
    for (var i = 0; i < this.pos.length; i++) {
        //create new html elements
    }
}

使用此关键字存储位置,因为其特定于对象。

即使你想把pos附加到showPlayList函数,那么showPlaylist.pos的概念也是错误的,因为要附加那个Player.prototype.showPlaylist.pos应该写。

答案 1 :(得分:1)

您的代码可能存在一些问题,首先,如前所述,pos成员位于this上。 this的值可能不是播放列表。

有关原型和价值的更多详细信息,请访问here