javascript类中的自动增量值

时间:2016-01-29 23:35:00

标签: javascript class oop object increment

每次实例化类的新实例时,我都会尝试自动增加属性值。这是我的类构造函数看起来的东西(我把它抽象了一下):

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

我不想定义一个在全局范围内递增的初始变量。任何人都可以向我暗示正确的方向吗?干杯!

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

否则,我要提出Mike C所描述的解决方案,但他已经设定了一个包含这样一个想法的好答案,所以......