Method Definition Without "Function" Keyword: An ES6 Feature
In this article, we delve into an unusual observation: the successful execution of an object method without the "function" keyword. This curious behavior has been encountered in certain browsers, leaving us pondering its origins and implications.
The object method definition in question is:
var module = { foobar(arg1) { alert(arg1); } };
In traditional JavaScript syntax, this method would be declared as:
foobar: function(arg1) {}
However, the omission of "function" in this instance has raised questions about its compatibility and its potential connection to ES6 functionality.
Answer
Yes, this method definition is a consequence of ES6's new syntax for object methods. In ES6, a shorthand notation allows for more concise method definitions without the "function" keyword. This is achieved through the use of arrow functions, which provide a simplified alternative to traditional functions.
The ECMAScript 6 specification states the following regarding 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() {} };
Therefore, the method definition without "function" is a valid ES6 syntax that is supported by certain browsers. However, as noted in the original question, this feature may not be universally compatible across different browser versions.
The above is the detailed content of Can ES6 Object Methods Be Defined Without the 'function' Keyword?. For more information, please follow other related articles on the PHP Chinese website!