javascript模块使用闭包和函数

时间:2016-04-12 01:09:26

标签: javascript

此代码是我第一次尝试创建一个模块,该模块在给出昵称时给出全名。但我在结果中未定义,不知道为什么。感谢

let nameProper = (function nameProper (nameShort) {
  let names = {
    "fj": "Fred Johnson"
  };
  return function () {
    return names['nameShort'] || nameShort;
  };
}());

let myName = nameProper('fj');

2 个答案:

答案 0 :(得分:2)

const nameProper = (function () {
  const names = {
    fj: "Fred Johnson"
  };

  return function (nameShort) {
    return names[nameShort] || nameShort;
  };
})();

let myName = nameProper('fj');

您需要将参数传递给内部函数,而不是立即调用的结束函数。

答案 1 :(得分:0)

可替换地:

let nameProper = function(nameShort)
{
    return this.names[nameShort] || nameShort;
}
.bind
({
    names:
    {
        "fj": "Fred Johnson"
    }
});

let myName = nameProper('fj');