javascript - 如果没有 "function"关键字,这个对象方法定义如何工作?

标签 javascript function methods ecmascript-6 shorthand

我通过不小心遗漏了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");

最佳答案

How is it possible that this runs at all in any browser? Is is some sort of new ES6 functionality?

Yes .

...

Method definitions

A property of an object can also refer to a function or a getter or setter method.

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

In ECMAScript 6, a shorthand notation is available, so that the keyword "function" is no longer necessary.

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

...

关于javascript - 如果没有 "function"关键字,这个对象方法定义如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015721/

相关文章:

ios - 查找适合 iPad 屏幕的图像数量(不同尺寸)的算法

methods - 现有代码库中具有大量参数的重构方法

Java 方法 - 将方法作为参数

c++ - 从 Main 方法调用函数

r - 在 R 中的某个点求解(确定)一个函数

javascript - 如何触发 VueJ

javascript - Linux 上的 Karma 启动器

javascript - jquery比较img下面的高度和h2的高度

javascript - 防止图像调整 div 大小

C++从函数返回指向数组的指针的正确方法