0

JavaScript オブジェクトを操作しようとしていますが、あまりうまくいきません。これが機能しない理由はありますか?

function Tracking(){
    var choices = new Array();

}

Tracking.prototype.getChoice = function (key){
    return this.choices[key];
}
Tracking.prototype.setChoice = function (choice){
    this.choices.push[choice];
}   

function TrackingChoice(key, choice){
    this.key = key;
    this.choice = choice;
}

.....

    var tracking = new Tracking();

    var choices = new Array();
    choices.push(new TrackingChoice("purchase", true));
    choices.push(new TrackingChoice("listing", false));
    choices.push(new TrackingChoice("offers", false));
    choices.push(new TrackingChoice("messages", false));

    tracking.setChoice(choices);


    var a = tracking.getChoice(0);

var aTrackingオブジェクトのchoices配列がまだnullであるため、空です。これは私を混乱させます。

4

3 に答える 3

1

このようにしてみてください

   function Tracking(){
    this.choices = []; var count = 0;
    this.getChoice = function (key){
        return this.choices[key];
    };
    this.setChoice = function (choice){
        this.choices[count] = choice;count++;
    };
}
function TrackingChoice(key, choice){
    this.key = key;
    this.choice = choice;
}
var tracking = new Tracking();
var choices = new Array();
tracking.setChoice(new TrackingChoice("purchase", true));
tracking.setChoice(new TrackingChoice("listing", false));
tracking.setChoice(new TrackingChoice("offers", false));
tracking.setChoice(new TrackingChoice("messages", false));
var a = tracking.getChoice(0);
于 2013-11-09T07:10:13.737 に答える