【问题标题】:How does this object method definition work without the "function" keyword?如果没有“function”关键字,这个对象方法定义如何工作?
【发布时间】:2015-11-30 23:59:15
【问题描述】:

我不小心遗漏了function 关键字发现了这一点。通常,下面模块中的foobar 方法将被声明为foobar: function(arg1),但有趣的是,至少在某些浏览器中,以下工作有效,例如Chrome 版本 44.0.2403.157 m,但在 IE 11.0.9600.17959 中失败

这怎么可能在任何浏览器中运行?这是某种新的 ES6 功能吗?

var module = {
    foobar(arg1) {
        alert(arg1);
    }
};

module.foobar("Hello World");

【问题讨论】:

    标签: javascript function methods ecmascript-6 shorthand


    【解决方案1】:

    这怎么可能在任何浏览器中运行?是某种新的 ES6 功能吗?

    Yes.

    ...

    方法定义

    对象的属性也可以引用函数、getter 或 设置方法。

    var o = {
      property: function ([parameters]) {},
      get property() {},
      set property(value) {},
    };
    

    在 ECMAScript 6 中,可以使用简写符号,因此 不再需要关键字“function”。

    // Shorthand method names (ES6)
    var o = {
      property([parameters]) {},
      get property() {},
      set property(value) {},
      * generator() {}
    };
    

    ...

    【讨论】:

    • 如您所见,在第一种情况下,new o.preperty() 行为正常。使用速记方法名称,new o.property() 会引发错误。见here
    【解决方案2】:

    ES6 允许 "concise methods",正如您所发现的,它还不能跨浏览器兼容。

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2021-08-11
      • 2019-05-23
      • 2012-11-17
      相关资源
      最近更新 更多