2

I would like to make the getArea() function a prototype, and am not sure if this ES6 (?) format is automatically doing this for me, or do I still need to declare a prototype in a separate Object.prototype.method = function() {} construct?

class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    getArea() {
        return this.height * this.width;
    }
}
2
  • See the confirmation by yourself Commented Dec 11, 2017 at 15:43
  • Is there a reason you wouldn't just check for yourself? console.log(Polygon.prototype.getarea) Commented Dec 11, 2017 at 15:45

1 Answer 1

6

It is.

The ES6 class format basically translates to something like this:

function Polygon(height, width) {
  this.height = height;
  this.width = width;
}

Polygon.prototype.getArea = function() {
    return this.height * this.width;
};
Sign up to request clarification or add additional context in comments.

5 Comments

Further confirmation - I just compiled the code from the question using TypeScript and Babel and this is pretty much exactly the code that gets output.
An important distinction would be that the method would be non-enumerable.
I'm not sure how ES6 or ES5 syntax would really differ in that regard.
The ES5 syntax you're using makes it so getArea will show up when enumerating the properties of an instance. for (var x in new Polygon()) { console.log(x) }. But in ES6, because it's non-enumerable, getArea won't show up in the loop. To get that behavior in ES5 browsers, you'd use Object.defineProperty to add the method to the prototype.
Ah, good point. I don't think I realized that myself. Just tested it myself and that is definitely the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.