JavaScript:将参数传递给间接的匿名函数

时间:2011-12-07 15:07:05

标签: javascript closures

我想通过编写一个从闭包内返回一个对象的函数来实现JavaScript中的数据隐藏。这是错误的代码:

pokerObjects.getPokerCard = (function(f, s){
        // These are immutable, so hide them in the closure
        var face = (typeof f === 'number' ? pokerObjects.faces[f] :  f);
        var suit = (typeof s === 'number' ? pokerObjects.suits[s] :  s);

        return {
            to_s: function() { return face + " of " + suit; }
          };

      })(f,s);

我想要做的是能够使用两个参数调用函数getPokerCard并将这些参数传递给以括号方式定义的匿名函数。但是,当我尝试解析代码时,如上所述传递它们会给我ReferenceError: f is not defined

2 个答案:

答案 0 :(得分:2)

也许我没有正确理解你的问题,但似乎你想为pokerObjects.getPokerCard分配一个函数,它允许你以后调用pokerObjects.getPokerCard(f,s),它返回带有getFace的对象,getSuit和to_s。

pokerObjects.getPokerCard = function(f, s) {
    // These are immutable, so hide them in the function.
    var face = (typeof f === 'number' ? pokerObjects.faces[f] :  f);
    var suit = (typeof s === 'number' ? pokerObjects.suits[s] :  s);

    return {
        getFace: function() { return face; },
        getSuit: function() { return suit; },
        to_s: function() { return face + " of " + suit; }
    };
};

这可以完成同样的事情,同时仍然确保面部和西装保持隐藏。它们是函数中的范围变量。

答案 1 :(得分:0)

pokerObjects.getPokerCard = getPokerCard;

Card.prototype.toString = cardToString;

function getPokerCard(face, suit) {
  return new Card(
    typeof face === "number" ? this.faces[face] : face, 
    typeof suit === "number" ? this.suits[suit] : suit
  );
}

function Card(face, suit) {
  this.face = face;
  this.suit = suit;
}

function cardToString() {
  return this.face + " of " + this.suit;
}

JavaScript中没有私有。如果为数据公开getter,则数据隐藏没有意义。只需使用属性(如果你真的想要,则使其成为不可写的)