1

Possible Duplicate:
Javascript infamous Loop problem?

for (var i=0; i<songList.length; i++){
        test.init({
        });
}

var test = {
    init: function (params) {
        var my = this;

        var backend = WaveSurfer.Audio;

        if (!params.predrawn) {
            backend = WaveSurfer.WebAudio;
        }
        var id = playList.length;
        this.id = id;

        this.backend = Object.create(backend);
        this.backend.init(params);

        this.drawer = Object.create(WaveSurfer.Drawer);
        this.drawer.init(params);

        this.backend.bindUpdate(function () {
            my.onAudioProcess();
        });

        this.bindClick(params.canvas, function (percents) {
            my.playAt(percents);
        });

    playList.push(my);

When I debug this script: my id is 0 for the first element; but when I go into the second loop suddenly both ids become 1. How is this possible?

enter image description here

Community
  • 1
  • 1
Thomas
  • 1,678
  • 4
  • 24
  • 47

1 Answers1

4

Because first time playList is empty that why length of playlist is zero but after init call it has one items so length of playList become 1 for second init call so value of id depends on number of init call.

Since you are not creating any new object so every time my will reference same object. so any change in my will reflect in all pushed items in playlist.

Modified code: if you want add new item on each init call

var test = {
    init: function (params) {
        var my = {};

        var backend = WaveSurfer.Audio;

        if (!params.predrawn) {
            backend = WaveSurfer.WebAudio;
        }
        var id = playList.length;
        my.id = id;

        my.backend = Object.create(backend);
        my.backend.init(params);

        my.drawer = Object.create(WaveSurfer.Drawer);
        my.drawer.init(params);

        my.backend.bindUpdate(function () {
            my.onAudioProcess();
        });

        my.bindClick(params.canvas, function (percents) {
            my.playAt(percents);
        });

    playList.push(my);
Anoop
  • 23,044
  • 10
  • 62
  • 76