简体   繁体   中英

javascript module using closure and a function

This code is my first attempt to create a module which gives the full name when given the nick name. but I am getting undefined in the results and don't know why. Thanks

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

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

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

let myName = nameProper('fj');

You need to pass your argument to the inner function, not your closing function that is invoked immediately.

Alternatively:

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

let myName = nameProper('fj');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM