Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,954 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