Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this object method definition work without the "function" keyword?

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"); 
like image 681
Dexygen Avatar asked Sep 04 '15 18:09

Dexygen


People also ask

How does this work function?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword. Identifying the object in the current execution context when we invoke a method.

How does this keyword work in JavaScript?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.

Can we define a method for the object in JavaScript?

JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. Methods are functions stored as object properties.

What is the purpose of using object is method?

The Object.is() method determines whether two values are the same value.


2 Answers

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

...

like image 52
meagar Avatar answered Sep 19 '22 23:09

meagar


ES6 allows "concise methods" which, as you've discovered, aren't cross-browser compatible yet.

like image 22
Joseph Avatar answered Sep 22 '22 23:09

Joseph