Amaobi Victor
Amaobi Victor

Reputation: 67

Using an object as a method's argument in es 6

I am trying to take a new Point object as the argument of the plus method and then add to return the value. Point p will be correct in java but not in javascript.

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    plus(Point p) {
        console.log(p.a);
        return new Point(p.a + this.x, p.b + this.y);
    }
}

console.log(new Point(1, 2).plus(new Point(2, 1)));

// → Point{x: 3, y: 3}

Upvotes: 1

Views: 85

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You need to take the right properties and arguments without type.

class Point {

    constructor (x, y) {
        this.x = x;
        this.y = y;
    }

    plus (p) {
        return new Point(p.x + this.x, p.y + this.y);
    }
}

console.log(new Point(1, 2).plus(new Point(2, 1)));

Upvotes: 4

Related Questions