Glycerine
Glycerine

Reputation: 7347

Does JavaScript have classes?

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.

Upvotes: 86

Views: 48991

Answers (13)

Alireza Fattahi
Alireza Fattahi

Reputation: 45475

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++

Upvotes: -1

aakash4dev
aakash4dev

Reputation: 1176

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));

Upvotes: 0

Alireza Fattahi
Alireza Fattahi

Reputation: 45475

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

Upvotes: 5

willy wonka
willy wonka

Reputation: 1686

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.

Upvotes: 29

Mandeep Kaur
Mandeep Kaur

Reputation: 69

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

Upvotes: 2

Puneet Lamba
Puneet Lamba

Reputation: 791

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.

Upvotes: 0

James-Jesse Drinkard
James-Jesse Drinkard

Reputation: 15703

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.

Upvotes: 1

fthinker
fthinker

Reputation: 667

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.

Upvotes: 2

Christopher Altman
Christopher Altman

Reputation: 4896

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…

Upvotes: 7

ChristopheD
ChristopheD

Reputation: 116127

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.

Upvotes: 7

Steve Harrison
Steve Harrison

Reputation: 125480

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".

Upvotes: 122

Cesar
Cesar

Reputation: 4427

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.

Upvotes: -8

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

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

Yes, Javascript is an object oriented language.

Upvotes: 4

Related Questions