Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Practice Project User Interface Code

Christof Baumgartner
Christof Baumgartner
20,864 Points

Why not use classes?

Why don't we use the class-keyword? It is easier to read and everyone knows what you mean, because the syntax is similar to Java or other OOP languages. This would be first thing I expect from OOP-Javascript.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

In my opinion, this syntax is also the much more common one.

class Rectangle {

  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  calcArea() {
    return this.height * this.width;
  }

}

myrectangle = new Rectangle (5,10)
console.log(myrectangle.calcArea())

It also support static methods and prototypes.

2 Answers

Aaron Price
Aaron Price
5,974 Points

Javascript uses prototype objects, not class based objects. Even the es6 class keyword is basically just syntactic sugar around prototypes. So people expect it work one way, and it does something else entirely.

There's also a lot of criticism of class based oo in general, and functional programming is becoming popular again.

Christof Baumgartner
Christof Baumgartner
20,864 Points

ok, got it. Personally I like syntactic sugar sometimes. I think there are situations were the class-keyword is easier to read. However they could have mentioned why they don't use it.

But I got now what's the difference and why to write it as prototype object. E.g. it's nice to use, when you want to give new power to existing prototypes, like this

String.prototype.replaceAt=function(index, replacement) {
    return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
Phillip Kerman
PLUS
Phillip Kerman
Courses Plus Student 285 Points

What do you mean "...we use the class-keyword?"?? Are you saying this is the advice somewhere?

Aaron is correct that one criticism is that it LOOKs like other language's class keyword but behaves differently. Also, there are other ways to skin a cat--but it's not like you can never use the class keyword.

Was there a specific use case involved?