Is there a Javascript class?

Asked

Viewed 3,282 times

42

I am studying Javascript and saw some explanations that left me with doubts. Here at Stackoverflow I saw several questions about the possibility of creating an abstract class in Javascript.

But my question is this:: It is possible to create a Javascript class?

I’m asking this because I’m using it as a guide the website Developer.Mozilla found the following information:

"Javascript is a dynamic object-oriented language; it has types and operators, objects and methods. Its syntax comes from the Java languages and C, so many structures of these languages apply to Javascript also. One of the main differences is that Javascript has no classes; instead, the class functionality is made by prototypes of objects. The other main difference is that functions are objects, giving the functions the ability to store executable code and be passed as parameter to any other object."

The statement in bold left me with this doubt, because it is a reliable source for studies. What I understood is that there are no classes, but there are elements that can be used as classes.

I don’t know if that’s the correct interpretation.

What’s more, this same text says that Javascript is object-oriented, so I tried to understand why the statement of the non-existence of classes would be there.

I see many co-workers and professionals outside who say they instantiated Javascript classes, used such a class for such a purpose in Javascript.

With that I want to understand, it is correct to state that there are classes in Javascript or not?

6 answers

27


I think this settles the question.

4.2.1 Objects

Even though Ecmascript includes syntax for class Definitions, Ecmascript Objects are not fundamentally class-based such as those in C++, Smalltalk, or Java. Instead Objects may be created in Various Ways including via a literal Notation or via constructors which create Objects and then execute code that initializes all or part of them by assigning initial values to their properties.

It is what has written in the specification, that is, although there is syntax class the objects in Ecmascript are not fundamentally based on classes.

You program object-oriented, such as, but internally the behavior of a class in Javascript (prototype-based) is different than in Java and C# (class-based). The main difference is that in Java and C# class are abstract entities, that is, when I instate an object, they are created according to the class specification, the object is concrete, but the class is something abstract. In JS no, a class is also an object, it exists and the instance of the object is linked to the class. This is occurs through the JS prototype chain.

If you don’t have problems with English this book from the You Don’t Know JS series can solve all your doubts about Javascript classes and objects as well as learn more about how the prototype chain works in Javscript.

https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes

  • 1

    Perfect, that’s what it is.

  • So what works as a class in javascript is not exactly the same as language classes like java, C# etc? That’s it?

  • 4

    Yes. You program object-oriented, such as, but internally the behavior of a class in Javascript is different than in Java and C#. I think the main difference is that in Java and C# class are abstract entities, that is, when I instate an object, they are created according to the class specification, the object is concrete, but the class is something abstract. In JS no, a class is also an object, it exists and instance.

  • 2

    I think that comment (that should be part of the answer) very good. However I do not think that Javascript loses the right to call Class which ES6 added to the language just because it doesn’t behave with classical languages.

  • 3

    @Sergio Your argument is valid. In fact, the quoted excerpt of the specification is not normative, that is, it is only an explanation about the functioning of language. If we accept that "class" does not presuppose a certain kind of inheritance implementation, we can use the term in JS. But I personally find it confusing, and I think the new syntax should not even have been created (they will swear to me for this, hehe).

  • 1

    I also don’t think @Sergio, I actually think that this difference has a small impact on our everyday life as a developer. It’s more of an internal characteristic of language in my opinion. But it also allows us to face a certain problem from a different point of view because the JS prototype chain is subtle and powerful. I think I can say that in JS we can do everything that a classical object-oriented language does, and a few other things that they don’t do.

  • 1

    In short, we can use Javascript classes yes, we can program object-oriented Javascript yes. The only thing is that internally javascript classes are different from Java classes, but they behave basically the same.

  • 1

    @bfavaretto I also think it should not have been created, so Mootools continued to reign alone :) @Silvio I agree, and did not say before but to say contrary to what I said in my reply I think it is quite valid this reply +1.

  • 1

    Well, I think I understand better now. Of all the questions the bfavaretto was the one that helped me the most, but this comment you answered right after mine is very enlightening. I think my doubt is almost resolved. I will read again all the answers, compare them and see which one helped me most to accept as the answer to my question, because it can help others. But regardless of the answer chosen, all are very good and well explained. OBS.: Put your comment in the reply :)

  • There is an important advantage to this syntax for "fake" classes: IDES code helper tools can offer you better suggestions when they know what’s going on.

Show 5 more comments

24

Formally, Javascript has no classes. It is an object-oriented language, but one that implements prototypical heritage (see also). Even so, there have always been construction functions, which end up behaving like classes. Your friend is probably referring to one of these when he says he created a class. For example:

function Carro() {
    // inicializa o objeto
}
Carro.prototype.buzinar = function() {
    // implementar buzina aqui
}
var meuFusca = new Carro();
meuFusca.buzinar(); // funciona!

This creates an object that uses prototypical inheritance to gain access to the properties and methods that are in Carro.prototype. It is possible to create an object that inherits the same thing without having to invoke the constructor:

var meuFusca = Object.create(Carro.prototype);

This was only included in version 5 of the specification, amazingly enough - as it is closer to the traditional way of implementing prototypical inheritance.

In the current language specification (called ECMA-2015 or ES6), syntax with class (which was previously a reserved word), but has not yet been implemented in all browsers, or has been implemented with restrictions (in Chrome, for example, it only works on Strict mode; according to MDN, Opera does not yet support the new syntax, as IE; Edge and Firefox already do). A answer from Otto gives examples of this use. Our car example would look like this:

class Carro {
    constructor() { 
        // inicializa o objeto
    }

    buzinar() { // método da classe
        // implementar buzina aqui
    }
}

The result of this is the same as the forms that the language offered before, because prototypic inheritance continues to be used. The version with class is pure syntactic sugar, as Maniero already had mentioned.

Therefore, is it correct to state that JS has classes? Yes and no. Strictly speaking, no, but in practice, yes, since it has always been possible to work with something that behaves like a class, and now it is even possible to use the keyword itself class.

17

Javascript classes are introduced in Ecmascript 6 and are a syntax for existing legacy based on prototypes, in Javascript. Class syntax does not introduce a new object orientation inheritance model in Javascript. Javascript classes provide a simpler and clearer way to create objects and handle inheritance.

Declaring classes

One way to define a class is by using a class statement. To declare a class, you must use the class keyword followed by the name of the class (here "Polygon").

class Poligono {
  constructor(altura, largura) {
    this.altura = altura;
    this.largura= largura;
  }
}

Class Expressions

A Class Expression (class Expression) is another way to define classes. Class Expressions may or may not have (anonymous) names. The name given for a class expression is local to the class body.

// sem nome
var Poligono = class {
  constructor(altura, largura) {
    this.altura = altura; 
    this.largura= largura;
  }
};

// nomeada
var Poligono = class Poligono {
  constructor(altura, largura) { 
    this.altura = altura;
    this.largura= largura;
  }
};

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

Complementing we have a similar question right here from a look, it is a good material for study: What are classes, how to use them, and in Javascript?

14

Ecmascript 6 is the most recent specification of what is conventionally called Javascript has classes.

Previous versions work with prototypes that can perform the same in a different way. So they can be used as if they were classes.

There are the two forms of object orientation, by class and by prototypes. The language meets all the requirements of this paradigm. I’ve done this before with prototypes and now also with classes. You have more information on several other questions, such as that one.

Another question relevant on the specific subject for JS.

We can say that the new classes are only syntactic sugar, since it is possible to take an ES 6 code and translate it to older versions that are supported by several browsers. The classes are replaced by prototypes, that is, the class model follows the same model as the prototypes, nothing new has been introduced semantically in the language.

This process is called transpilling and occurs with other languages such as Coffescript and Typescript. It is very common with Javascript because it is the universal programming language of the web.

Typescript went a little further in object orientation and introduced other facilities such as genericity. All on the same basic JS model.

I’m not going to put examples because it’s full of other answers.

See also: What are the main differences between prototype-oriented programming and class-oriented programming?.

And in a generic way: What is the difference between a class and an object?.

14

Javascript has Classes yes. The language has always enabled Classes with some code ingenuity, but natively this was introduced with the ES6 (2015).

An example would be:

/**
 * Classes e herança
 * Example do http://www.es6fiddle.net/
 */
class Polygon {
  constructor(height, width) { // constructor
    this.name = 'Poligono';
    this.height = height;
    this.width = width;
  }

  sayName() { // método da classe
    console.log('Olá, eu sou um ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length=10) { // Possibilidade de ter valores por defeito em argumentos (introduzido também com a ES6)
    super(length, length); // chamar métodos da classe herdada
    this.name = 'Quadrado';
  }

  get area() { // método para calculo
    return this.height * this.width;
  }
}

let s = new Square(5);

s.sayName(); // => Olá, eu sou um Quadrado.
console.log(s.area); // => 25

console.log(new Square().area); // => 100

This example above live can be tested here: http://www.es6fiddle.net/ijfxrckq/

Even the ES6 version of Javascript was possible to create/simulate classes. This is possible because it is possible to create new instances with new which can be applied to functions and objects. In this way an instance of a prototype is created and hiding some methods inside that are not accessible to outside scopes are gathered the instruments for Classes.

One of the libraries that took this further (as early as 2006) was o Mootools. An example would be:

var Animal = new Class({
    initialize: function(age){
        this.age = age;
    }
});

var Cat = new Class({
    Extends: Animal,
    initialize: function(name, age){
        // calls initalize method of Animal class
        this.parent(age);
        this.name = name;
    }
});

var myCat = new Cat('Micia', 20);
alert(myCat.name); // alerts 'Micia'.
alert(myCat.age); // alerts 20.
  • 10

    Even at ES6 classes are simulated (even with the new syntax with class), the functioning is prototypical at all times.

  • Brother, in another question asked with the title "What are classes, how do you use them, and in Javascript?" , you gave an answer like this: "First of all I must say that Javascript does not have, yet, Classes." Here you are telling me that there are classes in javascript. Was that a change in the structure of language? If it was, can you please explain it to me? Thank you!

  • @Diegodesouzasilva exact, this is part of the new version of the language that was released in 2015 and that is being implemented in browsers and Node.js. I put the link in the answer too.

  • in the comment on default values for variables, 'default' has been translated as 'default' and not 'default'

  • @igrossiter because in Portugal we say "by default" translating "by default". "Default" values are also not quite exact... Hmmm to see if I can think of a better translation.

  • @Sergio Interestingly, in Brazil defect would be a glitch

Show 1 more comment

4

Here are some very basic examples, to understand logic in a very simple way, in addition to the ways already posted:

There are calls Factory Functions or factory functions. They function as objects. A very simple example:

function Fruit(name) {
    this.name = name;
    this.color = "red";
}

To work with them:

var apple = new Fruit('Apple');
apple.color = "red";

To add keys:

apple.prototype.info = function() {
    return this.color + ' ' + this.name;
};
apple.info // red apple

Or you can use literal objects themselves:

var fruit = {
    name: "apple",
    color: "red",
    info: function () {
        return this.color + ' ' + this.name;
    }
}

Or you can mix the two ways already said:

var fruit = new function() {
    this.name= "apple";
    this.color = "red";
    this.info = function () {
        return this.color + ' ' + this.name;
    };
}

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.