JS: Define method

By Xah Lee. Date: .

Define method

A method is just a Property that has value of Function .

// create a object. one of the property is a function
const jj = {
 name: "Alice",
 add1: function (x) {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4

// get property
console.log(jj.name);
// Alice
// method shorthand syntax
const jj = {
 name: "Alice",
 add1 (x) {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4

// get property
console.log(jj.name);
// Alice
// method by arrow function
const jj = {
 name: "Alice",
 add1: (x) => {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4

// get property
console.log(jj.name);
// Alice
// method can be added later as a property

const jj = { name: "Alice" };

jj.add1 = (x) => {
 return x + 1;
};

// calling the method
console.log(jj.add1(3));
// 4

// get property
console.log(jj.name);
// Alice