Search code examples
javascriptthisarrow-functions

Javascript Objects Arrow-function and this


Learning JS and behaviour of this keyword ... want to understand whats happening below

Declared a Class ( point2 )

class point2 {
    constructor(x,y) {
        this.x = x;
        this.y=y;
    }
    dump() {
        (print = () => {
            console.log(this.x + " " + this.y);
        }).call(this);
    }
}

p1 = new point2(1,2);
p1.dump(); // prints undefined 

But not sure why p1.dump() call is printing undefined

was thinking p1.dump() would setup this to point2 object, and then print arrow function would inherit this ( which would be point2 object) and hence expected it to print 1 2


Solution

  • p1.dump() returns undefined because you don't return anything.

    class point2 {
        constructor(x,y) {
            this.x = x;
            this.y=y;
        }
        dump() {
            (print = () => {
                console.log(this.x + " " + this.y);
            }).call(this);
    
            return true; // return something here and the console.log will have result
        }
    }
    
    p1 = new point2(1,2);
    p1.dump(); // undefined

    Try it on devtool

    undefined is what method returns. So because the method does not have return keyword so it will return undefined. 1 2 is logged out as expected.