2011-08-10 134 views
2

这是我的代码:参数传递到嵌套函数

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; 
    }; 
}; 

这是传递参数给一个嵌套函数的正确方法?这idid2this.deal()this.hit()是从Placemat()

+0

我不明白参数是什么? – zwol

回答

2

不,如果要使用发送到Placemat()的值,则需要在deal()hit()函数中引用它们。不要将它们列为这些功能的参数。

// 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; 
}; 

记住,参数仅仅是任何可以被传递给函数的标识符。 参数是实际通过的。

通过您定义的参数可以参考参数。所以要让你的函数引用发送到Placemat()的参数,你可以通过参数idid2来完成。

但是,如果这些嵌套函数定义自己的idid2参数,然后就是将这些功能引用。您将有效地遮蔽外部函数中的参数。

1

不,实际上,你通过身份证的第一个地方是什么?你不在功能中使用它们。

你这样做的方式是创建两个函数(hitdeal),每个函数都需要一个参数。这些参数恰好与外部函数的参数命名相同。