我试图在每次实例化该类的新实例时自动增加一个属性值。这是我的类构造函数的样子(我将其抽象了一点):
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创建一个可以递增的私有(private)变量。
var Playlist = (function() {
var nextID = 0;
return function(player, args) {
this.id = nextID++;
...
};
})();
关于javascript - javascript类中的自动增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096021/