javascript class 中的自动增量值

Auto increment value in javascript class

我试图在每次实例化 class 的新实例时自动增加一个属性值。这是我的 class 构造函数的外观(我将其抽象了一点):

var Playlist = function(player, args){
    var that = this;
    this.id = ?; //Should auto increment
    this.tracks = [];
    this.ready = false;
    this.unloaded = args.length;
    this.callback = undefined;
    this.onready = function(c){
        that.callback = c;
    };
    this.add = function(tracks){
        for(var i = 0; i < tracks.length; i++){
            this.tracks.push(tracks[i]);
            this.resolve(i);
        }
    };
    this.resolve = function(i){
        SC.resolve(that.tracks[i]).then(function(data){
            that.tracks[i] = data;
            if(that.unloaded > 0){
                that.unloaded--;
                if(that.unloaded === 0){
                    that.ready = true;
                    that.callback();
                }
            }
        });
    };
    player.playlists.push(this);
    return this.add(args);
};

var playlist1 = new Playlist(player, [url1,url2...]); //Should be ID 0
var playlist2 = new Playlist(player, [url1,url2...]); //Should be ID 1

我不想定义在全局范围内递增的初始变量。谁能向我暗示正确的方向?干杯!

您可以使用 IIFE 创建一个可以递增的私有变量。

var Playlist = (function() {
  var nextID = 0;
  return function(player, args) {
    this.id = nextID++;
    ...
  };
})();

您可以在代码中的某处设置 Playlist.id = 0,然后在构造函数中递增它并将新值分配给实例 属性,如:this.id = Playlist.id++.
这是因为它没有很好地封装,所以它可能被滥用。

不然的话,我本来是要提出Mike C描述的解决方案的,但是他已经给出了一个很好的答案,包含了这样的想法,所以...