Home >Web Front-end >JS Tutorial >Can Object Methods Be Defined Without the 'function' Keyword in JavaScript?
This article examines the curious case of an object method definition without the "function" keyword. While it might seem like a coding error, it can actually work in some browsers due to the introduction of a new ES6 functionality.
How does it work?
In ECMAScript 6 (ES6), a shorthand notation was introduced for method definitions within objects. This notation eliminates the need for the "function" keyword, as seen in the example below:
// Shorthand method names (ES6) var o = { property([parameters]) {}, get property() {}, set property(value) {}, * generator() {} };
Browser Support
This shorthand notation is supported in modern browsers like Chrome, but not in older browsers like Internet Explorer 11. This is why the example provided in the question works in Chrome but fails in IE 11.
Is this a bug or a feature?
This behavior is a result of the implementation of ES6 in modern browsers. It is not a bug but rather an intended feature that enables more concise and readable object method definitions.
Conclusion
The ability to define object methods without the "function" keyword is a notable ES6 feature that simplifies code and improves readability. While it may not be supported in all browsers, it is becoming increasingly common in modern JavaScript development.
The above is the detailed content of Can Object Methods Be Defined Without the 'function' Keyword in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!