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

Alex Watts
Alex Watts
8,396 Points

If JavaScript is Object Orientated, why does it not have classes? I am confused.

Hello,

I am starting to learn about OO programming. What I am confused about is that if JavaScript is OO why does it not use classes?

Thanks for your help!

3 Answers

Steven Parker
Steven Parker
231,261 Points

:point_right: JavaScript was designed with a different object paradigm.

While most languages rely on the class paradigm to represent objects, JavaScript has traditionally used the prototype paradigm. It takes a bit of getting used to if you're already familiar with doing things the other way, but has some interesting advantages.

However, I say "traditionally" because the changes made to the language last year include classes. So now classes are available, if you prefer to use them (the other approach still works). This and other new features are described in the new course Treehouse just released this week on Introducing ES2015.

Alex Watts
Alex Watts
8,396 Points

Thanks Steven, I am getting to grips with classes, how would you best describe them. Could you possibly included an example of a class and a prototype in JS.

Thomas Nilsen
Thomas Nilsen
14,957 Points

Javascript is actually one of very few languages where you can create an object without a class. So in a sense, it's much more OOP than for example Java (which technically is class oriented)

This is maybe not the best, but it shows you how one Object inherits from another using the prototype mechanism:

function Animal(type) {
    this.type = type;
}

Animal.prototype.printType = function() {
    return this.type;
};

function Deer(name) {
    Animal.call(this, 'deer');
    this.name = name;
}

Deer.prototype = Object.create(Animal.prototype);

Deer.prototype.identify = function() {
    console.log('Hello! My name is ' + this.name + ' and I\'m a ' + this.printType());
}




var d1 = new Deer('Mike');
d1.identify();      //Hello! My name is Mike and I'm a deer