minte9
LearnRemember



Methods

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

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

A.hello(); // Hello
A.world(); // World

This

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

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

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

A.sayHi(); // John
B.sayHi(); // Ilya



  Last update: 451 days ago