title | date | excerpt | categories | tags | share | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Javascript Function with *this* keyword |
2020-10-03 15:34:30 -0400 |
Good reference to the ... syntax for a function within an object literal |
|
|
true |
Good reference to javascript function using this keyword in an obect literal. Came from a webpage on different ways to write a js function.
Example 1
Function Shorthand methods: Shorthand method definition can be used in a method declaration on object literals and ES6 classes. We can define them using a function name, followed by a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces { ... } that delimits the body statements.
The following example uses shorthand method definition in an object literal: Note the ... syntax. Kinda cool!
const fruits = {
items: [],
add(...items) {
this.items.push(...items);
},
get(index) {
return this.items[index];
}
};
fruits.add('mango', 'banana', 'guava');
fruits.get(1); // banana
add() and get() methods in fruits object are defined using short method definition. These methods are called as usual: fruits.add(...) and fruits.get(...).