dopatraman
dopatraman

Reputation: 13908

passing parameters to nested functions

This is my code:

var Placemat = function(id,id2) {
    this.hand = document.getElementById(id);
    this.bucket = "";
    this.bucketspace = document.getElementById(id2);
    this.bucketvalue = 0;
    var that = this;
    this.deal = function(id) {
        shuffle();
        var card1 = deck.shift();
        var card2 = deck.shift();
        this.hand.innerHTML = card1 + ", " + card2;
    };
    this.hit = function(id2) {
        var card3 = deck.shift();
        this.bucket = this.bucket + deck.shift();
        this.bucketspace.innerHTML = this.bucket; 
    };
};

Is this the proper way to pass parameters to a nested function? This id and id2 in this.deal() and this.hit() are from Placemat().

Upvotes: 3

Views: 6206

Answers (2)

FishBasketGordo
FishBasketGordo

Reputation: 23142

No. In fact, what are you passing the id's in the first place? You don't use them in the functions.

The way you are doing it, you are creating two functions (hit and deal) which expect one argument each. Those arguments just happen to be named the same as the arguments to your outer function.

Upvotes: 1

user113716
user113716

Reputation: 322492

No, if you want to use the values that were sent to Placemat(), you need to reference them in the deal() and hit() functions. Not list them as parameters to those functions.

 // removed---------v
this.deal = function() {
    alert( id );  // <---- do something with the original argument
    shuffle();
    var card1 = deck.shift();
    var card2 = deck.shift();
    this.hand.innerHTML = card1 + ", " + card2;
};

 // removed--------v
this.hit = function() {
    alert( id2 );  // <---- do something with the original argument
    var card3 = deck.shift();
    this.bucket = this.bucket + deck.shift();
    this.bucketspace.innerHTML = this.bucket; 
};

Remember, the parameter is just an identifier for whatever may be passed to the function. The argument is what was actually passed.

You can reference the argument via the parameter you defined. So to have your functions reference those arguments sent to Placemat(), you can do so via the id and id2 parameters.

But if those nested functions define their own id or id2 parameter, then that is what will be referenced in those functions. You will have effectively shadowed the parameters in the outer function.

Upvotes: 3

Related Questions