重用返回内部函数的函数

时间:2019-01-22 17:31:16

标签: javascript closures

如何使f(“ Michael”)返回字符串“ Michael”?

我需要f()来产生“ Michael”,而f(“ Michael”)(“ Jackson”)来产生Michael Jackson

    function f (firstName) {
        var nameIntro = "This celebrity is ";
        
       function lastName (theLastName) {
            return nameIntro + firstName + " " + theLastName;
        }
        return lastName;
    }
    
    
    
    console.log(f ("Michael")("Jackson"))

I'm really after a solution for this..
The above original question was not precise enough..
f()='f'
f('it' ) == 'fit'
f()('x') == 'fox'
f()()('bar') == 'foobar'

2 个答案:

答案 0 :(得分:2)

如果环境需要原始值,则可以实现一个toString函数。

function f(firstName) {
    function lastName(theLastName) {
        return nameIntro + firstName + " " + theLastName;
    }
    var nameIntro = "This celebrity is ";

    lastName.toString = function () { return firstName; };
    return lastName;
}
    
console.log(f("Michael")("Jackson"));
console.log(f("Michael"));

答案 1 :(得分:0)

这是我的做法,在返回的函数中添加了显式属性。

function nameFormatter(firstName) {
    var intro = "This celebrity is ";

  function rest (lastName) {
    return intro + firstName + " " + lastName;
  }

  rest.firstName = firstName;
  return rest;
}

var f = nameFormatter("Michael")
console.log(f);
console.log(f.firstName);
console.log(f("Jackson"));