Does JavaScript have classes?
Asked Answered
B

13

86

A friend and I had an argument last week. He stated there were no such things as classes in JavaScript.

I said there was as you can say var object = new Object()

He says "as there is no word class used. It's not a class."

Who is right?


Note: This question was first asked before the introduction of class syntax in ECMAScript 6th Edition (2015). Even then, as remarked above, the presence of this syntax alone need not necessarily settle the question.

Briarroot answered 2/5, 2010 at 8:37 Comment(1)
I found this reddit thread that gives a lot of people's perspectives on this topic. The majority seem to be saying that es6 classes count as real classes, but of course there's some conflicting opinions. Anyone who wants to dive a little deeper into this question and develop their own opinion can take a peek: reddit.com/r/javascript/comments/8q6267/…Bartholomeus
C
121

Technically, the statement "JavaScript has no classes" is correct.

Although JavaScript is object-oriented language, it isn't a class-based language—it's a prototype-based language. There are differences between these two approaches, but since it is possible to use JavaScript like a class-based language, many people (including myself) often simply refer to the constructor functions as "classes".

Chapatti answered 2/5, 2010 at 8:46 Comment(4)
You can simulate classes using prototypes and prototypes using classes, e.g. look at he Prototype design pattern.Ahoufe
@SteveHarrison, JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. So this means javascript is becoming now class-based language?Minnick
yeah as a Java dev, I often point this out to people. Javascript has 'OBJECTS' but not classes. What people refer to as a 'class' is actually an object.Bufford
Even though ES6 classes are mostly syntax sugar, anyone wanting to disregard them as not being real will have to be careful not to use arguments that also exclude classes from other dynamic languages. Javascript classes have become just as real as a python class.Bartholomeus
C
29

Javascript is an object oriented programming language, nevertheless in 2015 with ECMA script 6 classes have been introduced and now is correct to use them like other class based languages like Java. Of course as pointed out by the user codemagician in his/her comment, there are some deep differences between how classes work in js and java or other "class based" programming languages.

Nevertheless now in js programming it is possible to use for example code like:

class Animal { 
  constructor(name) {
    this.name = name;
  }


class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

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

That has something in common with classical class-based languages. The problems still is the browser support of this new technology that is just at start at the moment. So it still is not good to use it on productions products. But I don't have any doubt that this issue is going to be solved fast.

Hence the question remains if js has become a class-based programming language because of the implementation of this new features or does it still remain an object prototyping oriented programming language.

Candelariacandelario answered 25/9, 2016 at 6:18 Comment(5)
@Bhargav Rao Hi. Tnx for the comment. I don't mean to be polemic but the question was "Does JavaScript have classes?" I said "Classes in js have been introduced in ECMA script 6 in 2015" This IMHO gives an updated answer to the question... Doesn't it? And also at the same time my response tries to "converse" with other devs about their point of view about this new EC6 situation. Might be I'm wrong, in this case I'm sorry for my mistake.Candelariacandelario
Can I humbly ask why about down votes so I can learn on my own mistakes? Tnx in advance.Candelariacandelario
I haven't down voted. I guess it's because of flags. Usually they're the culprits. Wait for a day or two. Other domain experts will see your post and vote accordingly. Don't worry much about these sudden down votes.Beanstalk
@Bhargav Rao Ah OK anyway I didn't say that was you to down vote: I didn't mean to accuse anybody, I was talking in general just hoping to get an explication to improve my behavior into stack overflow to be helpful for both myself and others on this awesome community: I'll take my time, I'm still new, ;-)Candelariacandelario
Your answer is misleading. It's not true to say "now is correct to use them like other class based languages like Java". Java is an OO class-based language. Instances of classes make copies of properties on each instance created. "classes" in JS are nothing more than syntactical sugar to wire up Objects Linked to Other Objects (OLOO) - the fundamental model on which JS is based. The OLOO model will always use the prototype chain to provide "inheritance" (in reality it's delegation), there is never a true copy of the "instance" properties. A "class" is not static as in a true OO language.Davenport
P
7

In Javascript pretty much everything is an object (objects can inherit from other objects). It does not have classes in the classical sense.

Although you can reproduce most of the functionality of traditional class definition / instantiation by function prototyping.

Pause answered 2/5, 2010 at 8:43 Comment(3)
"In Javascript everything is an object": not true. There are also primitive values, like undefined, null, etc.Gipson
void? does void exist in javascript - I'm as3 guy see... I've never seen void in js.Briarroot
@Briarroot The closest thing in JavaScript to AS3's void would be undefined as far as I can tell.Hylton
C
7

Listen to Douglas Crockford's talk here:
http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2

He directly addresses your question in his presentation:

The most controversial feature of the language is the way it does inheritance, which is radically different than virtually all other modern languages. Most languages use classes – I call them ‘classical languages’ – JavaScript does not. JavaScript is class free. It uses prototypes. For people who are classically trained who look at the language, they go: well, this is deficient. You don’t have classes, how can you get anything done? How can you have any confidence that the structure of your program’s going to work? And they never get past that. But it turns out…

Carcassonne answered 2/5, 2010 at 11:33 Comment(1)
Video is hosted on YouTube youtube.com/watch?v=RO1Wnu-xKoYEcklund
S
5

From You-Dont-Know-JS book at https://github.com/getify/You-Dont-Know-JS

Chapter 4: Mixing (Up) "Class" Objects

...

JS has had some class-like syntactic elements (like new and instanceof) for quite awhile, and more recently in ES6, some additions, like the class keyword.

But does that mean JavaScript actually has classes? Plain and simple: No

I am not going to copy and past other parts here but encourage to read chapter 3 & chapter 4 and run samples.

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch3.md

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch4.md

Southeastward answered 3/12, 2018 at 7:42 Comment(2)
great reference!Metzler
Fixed links: You Don't Know JS: this & Object Prototypes Chapter 3: Objects You Don't Know JS: this & Object Prototypes Chapter 4: Mixing (Up) "Class" ObjectsEcklund
P
4

By "language X has classes" people usually mean support of object oriented programming.

Yes, Javascript is an object oriented language.

Plumb answered 2/5, 2010 at 8:40 Comment(2)
JS is a functional languageDurrell
@Durrell Not even close. Having first-class functions does not make JavaScript a functional language.Genia
J
2

When I think of classes I think of types and the fact that classes allow me to define new types. In js you can't create new types. You can do all sorts of fancy oo stuff with prototypes but the fact that everything is still an object really hits home the class-less nature of js. I think that people using 'class' terminology when talking about js confuses the js as a prototype language vs js as a classical language even more than the ugly new operator. In short, just because js is OO doesn't imply that classes need to exist.

Jugglery answered 3/9, 2013 at 17:51 Comment(0)
K
2

In simple words - Yes. All you need is Babel.js transpiler, because all browsers does not support it except Chrome browser. A JavaScript class is a type of function. Classes are declared with the class keyword. We use function expression syntax to initialize a function and class expression syntax to initialize a class.

Here is an example of JavaScript class using function:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100
Knell answered 28/10, 2018 at 22:45 Comment(0)
M
1

To add in with the other answers, javascript does not have classes, although I'm starting to see statements where it is described as something like classes, but I believe that just confuses the issue.

JavaScript has prototypes, not classes, but they accomplish the same thing, prototypes are objects that define objects, hence the confusion.

A prototype is a representation of private internal state that a class would manage in Java for example. Instead of putting that internal state in a class and presenting an interface for manipulating behaviour, as in java, JavaScript exposes the data structure for JavaScript programs to manipulate directly.

This is the best description I've found on the subject, Prototypes are not Classes.

Marylnmarylou answered 7/11, 2015 at 16:33 Comment(0)
P
0

Although JavaScript didn't have classes prior to ES6, class-like behavior could be implemented in ES5 by sealing objects (thereby making objects non-extensible). In a sealed object, new properties and methods cannot be added and properties are not configurable. Property values can still be set and read. I say class-like, because there's one caveat. A sealed object's method definitions can still be modified. That's because property values can still be set, unless you change all method properties to be non-writeable -- at which point you've reproduced class behavior pretty closely using ES5.

Primarily answered 1/2, 2017 at 0:47 Comment(0)
A
0

Yes. Yes, javascript has classes and objects. This is an example of making blockchain by using javascript/NodeJS classes and objects:-

// coded by Alfrick Opidi in Smashing Magazine blog
// https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/

const SHA256 = require('crypto-js/sha256');
const fs = require('fs')

class CryptoBlock{
    constructor(index, timestamp, data, precedingHash=" "){
     this.index = index;
     this.timestamp = timestamp;
     this.data = data;
     this.precedingHash = precedingHash;
     this.hash = this.computeHash();     
    }
    computeHash(){
        return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)).toString();
    }   
}

class CryptoBlockchain{
    constructor(){
        this.blockchain = [this.startGenesisBlock()];     
    }
    startGenesisBlock(){
        return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain, its also called genisis", "0");
    }
    obtainLatestBlock(){
        return this.blockchain[this.blockchain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.precedingHash = this.obtainLatestBlock().hash;
        newBlock.hash = newBlock.computeHash();        
        this.blockchain.push(newBlock);
    }
}

 let smashingCoin = new CryptoBlockchain();

smashingCoin.addNewBlock(new CryptoBlock(1, "01/06/2020", {sender: "Iris Ljesnjanin", recipient: "Cosima Mielke", quantity: 50}));
smashingCoin.addNewBlock(new CryptoBlock(2, "01/07/2020", {sender: "Vitaly Friedman", recipient: "Ricardo Gimenes", quantity: 100}) );
fs.writeFile('genisis.json', JSON.stringify(smashingCoin), function (err) {
    if (err) throw err;
    console.log('Saved!');
  }); 
console.log(JSON.stringify(smashingCoin, null, 4));
Af answered 9/3, 2022 at 10:6 Comment(0)
S
-1

As mentioned in https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming the OOP concepts are implemented in java script in a unique way. You can use constructors and prototype to achieve OOP features. BUT it differs from other languages like Java and it is complicated :

The constructors and prototype features certainly have some relation to some of the OOP concepts described above.

  • constructors in JavaScript provide us with something like a class definition, enabling us to define the "shape" of an object, including any methods it contains, in a single place. But prototypes can be used here, too. For example, if a method is defined on a constructor's prototype property, then all objects created using that constructor get that method via their prototype, and we don't need to define it in the constructor.
  • The prototype chain seems like a natural way to implement inheritance. For example, if we can have a Student object whose prototype is Person, then it can inherit name and override introduceSelf().

But there is difference from "classical" OOP concepts and Javascript OOP

  • First, in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes.

  • Second, although a prototype chain looks like an inheritance hierarchy and behaves like it in some ways, it's different in others. The prototype chain's behavior is less like inheritance and more like delegation.

Now at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript mentions that the class is some how syntactic sugar for use OOP, under the hood, JavaScript still uses constructor and prototypes

It's worth keeping in mind that the features described here are not a new way of combining objects: under the hood, they still use prototypes. They're just a way to make it easier to set up a prototype chain.

So again there is no class as you used to see them in Java or C++

Southeastward answered 13/9, 2023 at 11:46 Comment(0)
P
-8

AFAIK Javascript use the prototype concept and it's not OO. That's means that you can't use the typical concepts of OOP like inheritance or polymorphism.

Patriciate answered 2/5, 2010 at 8:46 Comment(5)
JavaScript is a prototype-based programming language, which means it is an object-oriented language.Chapatti
I love this site because there is always something to learn ;)Patriciate
Both inheritance and polymorphism can be applied in Javascript.Vassal
shame on me, but stop downvoting this question please... i was young and silly :)Patriciate
This is my unofficial downVote.Heterochromatic

© 2022 - 2024 — McMap. All rights reserved.