简体   繁体   中英

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?

Edit: July 2017

JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

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

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

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

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.

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.

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…

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

Yes, Javascript is an object oriented language.

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

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.

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 .

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

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.

 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

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

Javascript is more of an Object based programming language rather than Object oriented programming language.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM