Is Javascript an Object-Oriented language?

Asked

Viewed 7,326 times

37

Many say that it is not an object-oriented language, because it is not possible to define classes in it, until its version Ecmascript 5, but with the use of constructing functions and prototyping it is possible to implement many of the concepts of Object Orientation, as Inheritance, Encapsulation, Overload etc.

So it certainly can be considered as an object-oriented language, although it’s prototyped?

  • 2

    It can be used object-oriented and not object-oriented.

  • 1

    @Paulohdsousa Just because there are no classes? I don’t like the orientation to objects via prototypes (Javascript case), but it is possible to argue that it is purest than class-based object orientation. Object inherits from object, for example.

  • @Pablo Almeida ok, so she is only object oriented.

  • 2

    Related: http://answall.com/questions/108548/existe-classe-em-javascript

5 answers

26

Yure, this will depend somewhat on your interpretation of what object orientation is.

for example, if you do a search on Dev Mozilla, you will see that according to their interpretation, Javascript is object oriented, but uses a model that does not use classes.

But it has to be said that prototype-based programming is not simply an OOP model, but a complete paradigm, in this case prototyping orientation.

I know the question comes down to ECMA5, but the ECMA6 brings the concept of class and heritage to the JavaScript, as in the example below taken from ECMAScript 6 — New Features

class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y)
        this.width  = width
        this.height = height
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        super(id, x, y)
        this.radius = radius
    }
}

even if you cannot use the ECMA6 (currently this is only feasible on the server side, as in a service made in Nodejs, since most browsers still do not support the ECMA6), you can still use the TypeScript and write codes as shown below (example taken from the documentation of TypeScript).

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}

reminded that the TypeScript is a JavaScript pre-compilado, something similar to what happens to the LESS and the SASS, then you will need a tool to convert the TypeScript in JavaScript, I particularly advise the use of Gulp, Grunt or BundleTransformer, after choosing a tool, you will have to download its respective module:

  • 1

    +1 by Typescript. <3

  • In the current version of Javascript it is possible to use classes ?

  • https://caniuse.com/#feat=es6-class

  • @Rogi93 if you are using Webpack or a polyfill, no problem, if you need support only the current browsers (see i can use site), no problem.

  • @Tobiasmesquita got it, obg.

  • Ah bro, how I love Typescript...

Show 1 more comment

21

TL;DR

I answer that in good measure in question What is the programming paradigm used by Javascript?. So I start by saying Javascript is multi-paradigm, among them object orientation.

Introducing

I talk about What is a paradigm?. By this definition JS is essentially imperative and has some features that facilitate object orientation. It is important to understand What is the difference between a class and an object?.

I talk about the Meaning of terminology: "Object oriented". There is no definitive answer there, there is much controversy about what OOP really is. I will talk here about what is most accepted in programming (not in design) and that can help define whether the language is object-oriented or not. There defines what is an object that is important to begin to understand if there is guidance.

There are other definitions I don’t like so much: What is "Object-oriented" and what other methods?. There is also a question whether There is a class in Javascript? and is an important reading. Further reading: Functional Programming and Object-Oriented Programming. What are and what are their main differences?.

Remembering that you can do object orientation up to Assembly. Or in C: Object oriented programming in C is possible?.

It’s not so clear whether it is or not

By all definitions I found JS is OO (as secondary paradigm). To a lesser degree than other languages. It is more specifically oriented to prototypes, which are still objects. A prototyping is a branch of object orientation. Language is not class-oriented.

If you still don’t believe, read the documentation that is considered official. Note that they do not say that language is object-oriented. In a certain way no language is of a paradigm. You apply paradigms to your code. But of course languages encourage a certain paradigm.

JS encourages object orientation? It depends on the OOP definition you use and depends on the definition of what it is to encourage.

You call members of a structure, including functions/methods, referencing themselves by the object primarily. Some say this is enough to be object-oriented. Others will say you need to be able to do inheritance, polymorphism and encapsulation.

  • An object can be created based on an existing one - which will be a prototype of this one (see example in other answers);
  • an object can assume different behaviors consistently with its "family";
  • an object can hide the details of how it works.

It can be argued that syntax is not the most convenient to do this. But it is very easy to understand how it works. There are specific mechanisms that "encourage" to do these things. If they are enough I do not know, I think that there we fall into subjectivity. Objectively the mechanisms exist.

Some say that it is necessary to abstraction and/or overload operators. But there are few sources that cite these characteristics as mandatory and are not the most reliable. It is possible to do abstraction in JS, but there is no specific mechanism. Anyway it is one more thing than design. Operator overload doesn’t really have anything, but it’s a controversial feature if it’s part of OO. Java doesn’t do this and no one questions whether the language is object-oriented.

As a matter of fact, I know a lot of people who don’t find class syntax that convenient. Of course, they are so used to the prototypes that it makes it difficult to adapt.

On the other hand there are those who say that OOP is about the code reuse. JS is one of the simplest languages to get this. If you say OO is to put state together with behavior, it is quite easy, the fact that it is optional to do so does not change anything.

There is no purity in JS. But what language is pure? Nor is it a good feature.

The fact that it is prototypeoriented does not eliminate the fact that it is object oriented as well as it does not eliminate the fact that it is mainly imperative.

SE6

Ecmascript6 brought the classes to the language. Note that there were no important semantic changes. Basically there is a new syntax to do what was already possible, now with classes. Syntax is important, of course. We always say that C can be programmed object-oriented, even without the language being. JS had no facility to write classes, although objects could be created without them.

Now JS is oriented to prototypes and classes. Has anything changed in relation to object orientation? I don’t think so. If nothing has changed, it seems that the language was already object-oriented before classes existed.

Who can’t use ES6, can use Typescript and have object orientation in its classical form (see more).

Completion

I consider that the language can be called object-oriented, I think most people think so. It makes little practical difference to know this, but it’s useful information that can help you better understand what you’re doing, which I always stand for.

17

To be object oriented a language must meet the 4 pillars that are Abstraction, Encapsulation, Inheritance and Polymorphism.

In Java Script we can apply the 4 concepts easily as shown below:

Abstraction
Simplifying is the step of modeling a real-world object with identity, properties and methods. This is done easily with JS:

// Define "classe" Pessoa
function Pessoa(nome, idade) {
    this.nome = nome;
    this.idade = idade;
}

// Toda pessoa tem uma método fazAniversário
Pessoa.prototype.fazAniversario = function() {
    this.idade++;
}

// Define classe Funcionario
function Funcionario(nome, idade) {
    Pessoa.call(this, nome, idade);
    this.salario = null;
}

// Todo funcionário herda de Pessoa
Funcionario.prototype = Object.create(Pessoa.prototype);

// Teste
var joao = new Funcionario('João', 25);
joao.fazAniversario();
alert(joao.idade); // 26

Encapsulation, Heritage and Polymorphism

// define a classe Person
function Pessoa() {}

Pessoa.prototype.caminhar = function(){
  alert ('Estou Caminhando!');
};
Pessoa.prototype.dizOi = function(){
  alert ('Oi!');
};

// define a classe  Estudante
function Estudante() {
  // Chama o método parente
  Pessoa.call(this);
}

// herda de Pessoa
Estudante.prototype = new Pessoa();

// corrigir o ponteiro construtor porque aponta para Pessoa
Estudante.prototype.constructor = Estudante;

// adiciona o método dizOi
Estudante.prototype.dizOi = function(){
  alert('Oi, eu sou estudante');
}

// adiciona o método dizTchau 
Estudante.prototype.dizTchau = function(){
  alert('tchau');
}

var estudante1 = new Estudante();
estudante1.dizOi();
estudante1.caminhar();
estudante1.dizTchau();

// check inheritance
alert(estudante1 instanceof Pessoa); // true 
alert(estudante1 instanceof Estudante); // true

Using Object.create the inheritance line should be:

Estudante.prototype = Object.create(Pessoa.prototype);

In the above example the student did not need to know how the method walk() of classe Pessoa would be implemented, but can still use this method; classe Estudante does not have explicit need to define the method since we do not want to change it. This is called encapsulation.


Although it is not like the other language to apply the concepts of object orientation, JS allows to perform all of them. I believe that JS can rather be considered OO.

I hope I’ve helped.

Sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
http://tableless.com.br/introducao-a-programacao-orientada-a-objetos-em-javascript/
This is a correct example of Javascript inheritance?

12

Many say it is not an Object-Oriented language, so don’t it is possible to define classes with it

  1. There is an object called Object
  2. Object has a function called create
  3. create creates a new object based on a pre-existing object
  4. Object has an object called prototype
  5. All objects are based on Object.prototype
    • Except those created by Object.create(null)

Objects that have objects creating new objects based on objects. What could be more object oriented than this?

Javascript is still object-oriented only because other languages confuse the concept of classes with the paradigm. Classes have more to do with static typing than object orientation.

After all, who said that it takes a predefined "plan" to create objects? Javascript does not need this paraphernalia. All you need is an object that creates new objects: the function create.

Inheritance

We can create an object based on another. This way, it will inherit the properties of its base:

const outro = Object.create(null);
const um = Object.create(outro);

outro.propriedade = 'valor';

um.propriedade;                       // 'valor'

Overload

If an object has a property, it is used instead of inheritance:

um.propriedade = 'outro valor';

outro.propriedade;                    // 'valor'
um.propriedade;                       // 'outro valor'

Encapsulation

Objects have properties. It is possible to configure them to perform functions get and set.

11

Yes, POO can be used in Javascript. But just like in PHP, you may not use.

Object-Oriented Programming is a programming paradigm that uses abstraction to create models based on the real world. POO uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Currently, many popular programming languages (such as Java, Javascript, C #, C++, Python, PHP, Ruby, and Objective-C) allow object-oriented programming (POO).

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

  • It can be used so it means she’s not, right?

  • I can’t tell if it is or not. I believe which it is not. But it is one of the languages that allows. So you can play for the same haha POG group

  • 1

    Group of POG? "Gambiarra-oriented programming"? Anyway, I’m from the school that says that JS is OO enough to be considered object-oriented, I don’t see anything offensive in saying that. And your answer apparently contradicts your comment, where you say you can use POO, but say that believeth not be object oriented, since object oriented programming is done with object orientation...

  • Correction: Certainly, I contradicted my comment. It is written in Mozilla that it is, but I am not aware that this information is correct, but it is a great influence. Thank you

Browser other questions tagged

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