This question already has answers here:
How does this object method definition work without the “function” keyword?

(2个答案)


5年前关闭。




我在使网站在Internet Explorer(IE9)中运行时遇到一些问题,我发现我们已通过以下方式在javascript对象中定义了一个函数:

var test = {
    a : function(){alert(123);},
    blafasl(){$("#test").text("456");},
    b : function(){alert(678);},
}

test.blafasl();
//test.b();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'></div>


在Chrome和Firefox中,代码可以正常工作,但在IE9中,它会生成错误消息。

“blafasl”的定义是否有效(以及它如何工作)?
还是IE出现错误是正确的?

当我将blafasl定义更改为时,它可以在Chrome,Firefox和IE中运行:blafasl: function(){....},
我发现了这个:http://www.bryanbraun.com/2014/11/27/every-possible-way-to-define-a-javascript-function,但它不涵盖我的问题...

问候
马丁

PS:这是上面代码的缩略语:http://jsfiddle.net/zjobwd89/2/

最佳答案

这是ES6对象文字:
https://github.com/lukehoban/es6features#enhanced-object-literals

您可以这样写:

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

关于javascript - 在没有属性名称的javascript对象中定义函数是否有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33918846/

10-12 12:57
查看更多