这个对象方法定义如何在没有“函数"的情况下工作?关键词? [英] How does this object method definition work without the "function" keyword?

查看:26
本文介绍了这个对象方法定义如何在没有“函数"的情况下工作?关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var 模块 = {foob​​ar(arg1) {警报(arg1);}};module.foobar("Hello World");

解决方案

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

.><块引用>

...

方法定义

一个对象的属性也可以引用一个函数或者一个getter或者setter 方法.

var o = {属性:函数([参数]){},获取属性(){},设置属性(值){},};

在 ECMAScript 6 中,可以使用速记符号,以便不再需要关键字function".

//简写方法名称(ES6)var o = {属性([参数]){},获取属性(){},设置属性(值){},* 发电机() {}};

...

I discovered this by accidentally leaving off the function keyword. Ordinarily the foobar method in the module below would be declared as foobar: function(arg1), but interestingly the following works, at least in some browsers, e.g. Chrome Version 44.0.2403.157 m, but it fails in IE 11.0.9600.17959

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

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() {}
};

...

这篇关于这个对象方法定义如何在没有“函数"的情况下工作?关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆