Is there a JavaScript class?

35

I'm studying JavaScript and saw some explanations that left me with doubts. Here in StackOverflow I saw several questions about whether to create an abstract class in JavaScript.

But my question is: Is it possible to create a class in JavaScript?

I'm asking this because I'm using the developer.mozilla site I found the following information:

  

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

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

I do not know if this is the correct interpretation.

Moreover, this same text says that JavaScript is object oriented, so I tried to understand why the assertion of non-existence of classes would be around.

I see many co-workers and professionals who say they instantiated classes in JavaScript, used that class for that purpose in JavaScript.

    
asked by DiChrist 15.01.2016 в 17:55

6 answers

20

I think this solves the issue.

  

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 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's what you've written in the specification, that is, although the syntax class exists the objects in ECMAScript are not fundamentally class-based.

You program object-oriented, just like, but internally the behavior of a Javascript class (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 instantiate an object, they are created according to the specification of the class, the object is concrete, but the class is something abstract. In JS no, a class is also an object, it exists and instance of the object is bound to the class. This is through the JS prototype chain.

If you do not have problems with English this book in the series You Do not Know JS can heal all your doubts about classes and objects in Javascript as well as learn more about how the prototype chain works in Javscript.

link

    
15.01.2016 / 18:42
17

Formally, JavaScript has no classes. Rather, it is an object-oriented language, but it implements prototypical inheritance ( see also ). Even so, there have always been the constructor functions, which end up behaving like classes. Probably your friend is 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 access properties and methods that are in Carro.prototype . You can create an object that inherits the same thing without having to invoke the constructor:

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

This has only been included in version 5 of the specification, incredible as it may seem - since it is closer to the traditional way of implementing prototypical inheritance.

In the current language specification (called ECMA-2015 or ES6), the syntax with class (which was previously reserved word before) has been introduced, but has not yet been implemented in all browsers, or has been implemented with (in Chrome, for example, it only works in strict mode , according to MDN, Opera does not yet support the new syntax, just as IE, Edge and Firefox already support). The Otto's answer 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 of the forms that the language already offered before, because the prototypical inheritance continues being used. The class version is pure syntactic sugar, as the bigown already had mentioned .

So, is it correct to say 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 as a class, and now it is even possible to use the keyword class .

    
15.01.2016 в 18:37
16

JavaScript classes are introduced in ECMAScript 6 and are a syntactic for existing prototype-based inheritance in JavaScript. The syntax for classes does not introduce a new object orientation inheritance model in JavaScript. JavaScript classes provide a simpler and clear way to create objects and deal with inheritance.

Declaring classes

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

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

Class Expressions

A class expression is another way to define classes. Class expressions can have names or not (anonymous). The name given to a class expression is local to the body of the class.

// 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: link

Complementing we have a similar question right here at a glance, it's a good study material: What are classes, how do you use them, and JavaScript?

    
15.01.2016 в 18:00
13

JavaScript has yes classes. Language has always enabled Classes with some code ingenuity, but natively this has been 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 above live example can be tested here: link

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

One of the libraries that took this deeper (already in 2006) was 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.
    
15.01.2016 в 18:05
12

EcmaScript 6, which is the latest specification of what has been called JavaScript has classes a>.

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

There are 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 it does with classes as well. You have more information on a number of other questions, such as this .

Another relevant question relevant to 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. Classes are replaced by prototypes. That is, the class model follows the same model of prototypes. Nothing semantically new has been introduced into 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 web programming language.

TypeScript went a little further on object orientation and introduced other features such as gen- eracity. All over the same basic JS template.

I will not put examples because it is full in the other answers.

    
15.01.2016 в 18:01
5

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

There are Factory Functions calls 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 the literal objects themselves:

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

Or you can merge the two already-mentioned ways:

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

Font

    
15.01.2016 в 18:12