I have a JavaScript object:
var methods = {
classStyle() {
console.log('Class style function');
},
traditionalStyle: function() {
console.log('Traditional style function');
},
arrowStyle: () => {
console.log('Arrow style function');
}
};
methods.classStyle();
methods.traditionalStyle();
methods.arrowStyle();
The output is as expected:
(index):70 Class style function
(index):74 Traditional style function
(index):78 Arrow style function
My questions are:
The "class style function" (shorthand method) is very similar to a regular function. The only difference is that it can't be used as a constructor (i.e. called with new
), and because of that it doesn't have a prototype
property. As for arrow functions, see Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?. In a nutshell, arrow functions don't bind their own this
and arguments
, and can't be used with new
.
Is it down to personal preference? Or do the inner workings change?
In ES6+ there's no reason to use the traditional function syntax in objects, because the shorthand methods syntax is simpler and safer, because if you accidentally try to use a method as a constructor, you'll get an error. As for arrow functions, you can use them only if you don't need to access the object using this
.
Just as a complement, as it was mentioned, first and second are not the same. One major difference is where and how they are available. See this snippet, you'll see that method definitions are available when the object is created, but not the function declaration.
This means that when you define with the traditionnal style, you cannot use it elsewhere in the object, it's going to be undefined. Class style will be available, which is a huge difference.
methods = {
classStyle() {
//console.log('class this is', this);
return 'class';
},
traditionalStyle: function() {
//console.log('traditional this is', this);
return 'tradition';
},
arrowStyle: () => {
console.log('arrow this is', this);
},
testFn() {
console.log('class is', this.classStyle);
console.log('traditionnal is', this.traditionnalStyle);
},
get classProp() {
return this.classStyle();
},
get traditionnalProp() {
return this.traditionnalStyle();
}
};
methods.testFn();
console.log(methods.classProp);
console.log(methods.traditionnalProp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With