What are classes, how do you use them, and JavaScript?

9

I started studying programming and JavaScript for 3 months, but so far only in technique. However, I realized that it is much easier to understand the concept of object orientation. I already know that objects in programming are like real-life objects that interact with each other with their functions and attributes to create something.

I have already understood the concepts of native objects, declared objects, window and DOM.

I just need to understand the concept of class and how to create classes in JS.

And, after all, what advantages will classes give that only objects will not give?

What are instances? Are the objects of the class itself?

Why is the toString() method present in Object and Function objects at the same time?

    
asked by anonymous 11.10.2014 / 08:44

1 answer

12

First of all I must say that JavaScript does not yet have Classes. This will change with the implementation of ES6.

Some libraries such as MooTools use the possibility that JavaScript has to extend prototype to create the functionality that a Class has in classic programming languages.

The idea of Classes is very useful when you want to share certain features that are shared by different pieces of code. Using the new constructor creates a new instance of the Class that is free of its original in the sense that we can change it without changing its original / prototype.

The same does not happen with objects. By doing var objA = objB we are creating a reference for the same object and changing one we change the other.

However, it is possible to create a new object with inheritance, that is, to define an object or function from which we created a new instance. Example:

    function Pessoa(nome, idade) {
        this.nome = nome;
        this.idade = idade;
        this.nascido = function () {
            var anoAtual = new Date();
            return Math.abs(anoAtual.getUTCFullYear() - this.idade);
        }
        this.saudacao = 'Olá ' + nome;
    }
    var a = new Pessoa('António', 30);
    console.log(a.nascido()); // 1984
    console.log(a.saudacao); // Olá António
    alert(a.nascido() + '\n' + a.saudacao);

But this is not a Class but a new instance of an object.

Notice that:

typeof Pessoa // dá 'function'
typeof new Pessoa() // dá 'object'

Another difference between objects and Classes is the possibility of having private methods (and here I am referring to the Classes that ES6 will bring and what MooTools introduced already in 2009).

Example ES6 Class:

class Car {
    constructor(make) { // conceito novo em Javascript, para iniciar a Classe
        this.make = make;
      this.currentSpeed = 25;
    }

    printCurrentSpeed(){ // método da Classe
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
}

Now that we have a Class we can use it to create a new Class which is an extension / continuation of this:

class RaceCar extends Car { // semelhante à herança do prototype
    constructor(make, topSpeed) {
        super(make); // usando a palavra super chamamos o contrutor da Classe pai desta nova
        this.topSpeed = topSpeed;
    }

    goFast(){
          this.currentSpeed = this.topSpeed;
    }
}

let stang = new RaceCar('Mustang', 150);

stang.printCurrentSpeed(); // velocidade atual: Mustang is going 25 mph.
stang.goFast(); // chamar o método que acelera à velocidade máxima
stang.printCurrentSpeed(); // velocidade máxima: Mustang is going 150 mph.

Example (ES6): link

This feature and possibility to add new features, calling parent class methods and private methods are characteristic of Classes. This way you can make a more DRY code with Classes that have common parts and other Classes that import this common functionality without having to retype the code.

The same example using a MooTools class (which can be used in current code):

var Car = new Class({
    initialize: function (make) {
        this.make = make;
        this.currentSpeed = 25;
    },

    printCurrentSpeed: function () {
        console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
})

var RaceCar = new Class({ //inheritance
    Extends: Car,
    initialize: function (make, topSpeed) {
        this.parent(topSpeed)
        this.topSpeed = topSpeed;
    },

    goFast: function () {
        this.currentSpeed = this.topSpeed;
    }
})

jsFiddle: link

    
11.10.2014 / 09:05