What are classes, how do you use them, and in Javascript?

Asked

Viewed 383 times

9

I started studying programming and Javascript 3 months ago, but so far only in technique. However I realized that it makes it very easy 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 already understand the concepts of native objects, declared objects, window and GIFT.

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

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

What are instances? They are the class objects themselves?

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

1 answer

12

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

Some libraries like Mootools use the possibility that Javascript has to extend the prototype to create the functionality a Class has in classical programming languages.

The idea of Classes is very useful when we want to share certain features that are shared by pieces of different code. Using the builder new a new instance of the Class is created 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. Making var objA = objB we are creating a reference to the same object and changing one we change the other.

It is however possible to create a new object with inheritance, that is, to define an object or function from which we create 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 refer to the Classes that ES6 will bring and what Mootools introduced in 2009).

Example of Class ES6:

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 that 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): http://www.es6fiddle.net/i14nv13e/

This functionality and possibility to add new features, call parent class methods and private methods are characteristic of the Classes. This way you can make a more DRY code with Classes that have communs and other Classes that import this common functionality without having to re-write 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: http://jsfiddle.net/yc52LL7s/

  • 1

    Wait a minute, what is ES6? What is protoype? is a native object? In this case js only works with objects inside objects?

  • 1

    @ropbla9 sobre prototype: http://answall.com/q/15239/129 e http://answall.com/questions/29864/quando-utilizar-prototype-js . ES6 is version 6 of Javascript that is already being implemented in some modern browsers.

Browser other questions tagged

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