Skip to content

Latest commit

 

History

History
41 lines (35 loc) · 1.33 KB

2020-10-02-Javascript-this-examples.md

File metadata and controls

41 lines (35 loc) · 1.33 KB
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
programming
programming
javascript
syntax
functions
this keyword
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(...).