PROGRAMMING     CLIMBING

  minte9
reminder




Last update:   25-01-2022

Methods

A function that is the property of an object is called method.
 
/**
 * In JavaScript actions are represented by functions in properties.
 * 
 * We can also use a shorthand syntax.
 */

let A = {
    name: "John",
    age: 30
};
A.sayHi = function() {
    console.log("Hello");
};
A.sayHi(); // Hello


let B = {
    'name': 'Sam',
    age: 20,
    sayHi() { // same as "sayHi: function()"
        console.log("World");
    }
}
B.sayHi(); // World

This

Sometimes object method needs to access object properties.
 
/**
 * To access the object itself ...
 * a method can use the this keyword.
 * 
 * Arrow functions have no 'this', 
 * it is taken from the outer normal function.
 */

let A = {
    name: "John",
    sayHi() {
        console.log(this.name);
    }
};
A.sayHi(); // John


let B = {
    name: "Ilya",
    sayHi() {
        let arrow = () => console.log(this.name);
        arrow();
    }
};
B.sayHi(); // Ilya

Questions     github Objects
Constructor
        A B C D E F
🔔
1/1