这是我的代码:
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;
};
};
这是将参数传递给嵌套函数的正确方法吗? this.deal()
和 this.hit()
中的 id
和 id2
来自 Placemat ()
。
最佳答案
不,如果您想使用发送到 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()
的参数,您可以通过 id
和 id2
参数来实现。
但是如果那些嵌套函数定义了它们自己的 id
或 id2
参数,那么 that 就是那些函数中将引用的内容。您将有效地隐藏外部函数中的参数。
关于javascript - 将参数传递给嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7016482/