JS:为什么不返回带有“功能”字样的内部功能?

时间:2019-01-22 15:25:54

标签: javascript closures

如果我要创建工厂函数foo,为什么不将内部函数返回为function noiseMade()而不是仅仅返回noiseMade()呢?

function foo() {
    let sound = "buzz"
    return {

        noiseMade() {

            return "I make" + sound
        }

    }
}

2 个答案:

答案 0 :(得分:2)

通过评论总结我们的对话。 对象中的函数支持的语法:

{
  makeNoise: function() {}
}

// ES6 and above
{
  makeNoise() {},
  makeAnotherNoise: () => {} // behave a bit different, read about arrow functions for more info
}

如果要从另一个函数返回一个函数,则可以:

const makeNoise = () => {
  const sound = 'bork';
  return () => { console.log(sound) };
} 

还有另外一条免费评论:)最好使用verbs作为函数名,因为函数通常是do的东西:)

答案 1 :(得分:1)

您提到的语法:

const obj = {
  propertyName() { ... }
};

是ES6中引入的shorthand method declaration

等效于经典声明:

const obj = {
  propertyName: function fnName() { ... }
};