Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in JavaScript OO methodology

Tags:

javascript

I am trying to learn more about JavaScript OO Programming, but am seeing conflicting methods to create a "Class"-like object. I am wondering if there are any substantial differences in these two methods:

Method 1

function Person(name){
    this.name = name;

    this.setName = function(val){
        this.name = val;
    }

    this.getName = function(){
        return this.name
    }
}

var John = new Person("John");

Method 2

function Person(name){
    var exports = {};
    exports.name = name;

    exports.setName = function(val){
        this.name = val;
    }

    exports.getName = function(){
        return this.name
    }

    return exports;
}

var Bob = Person("Bob");

I have seen these two methods used for creating a complex JavsScript object. I have even seen large JS plugins like jQuery use method 2 instead of method 1 to set up their jQuery functions. Is one of these faster or more efficient than the other in any way?

like image 735
Matt Hintzke Avatar asked May 28 '14 18:05

Matt Hintzke


People also ask

Is JavaScript functional or OO?

JavaScript can function as both a procedural and an object oriented language. Objects are created programmatically in JavaScript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like C++ and Java.

What is OO JavaScript?

a style of Object-oriented programming (OOP) in which inheritance occurs via defining classes of objects, instead of inheritance occurring via the objects alone. The most popular model of OOP is class-based. But as I mentioned, JavaScript isn't a classed-based langauge – it's is a prototype-based langauge.

What are the object-oriented features of JavaScript?

In this article we learned about classes, inheritance, encapsulation, abstraction, polymorphism and composition. These are all key concepts in the OOP world. And we've also seen various examples of how OOP can be implemented in JavaScript.

What are the Oops concepts supported by JavaScript?

This article explains objects, classes, encapsulation, and inheritance with examples. You will see how classes and objects can be created in JavaScript. Objects in OOP have to have relationships, which can be through aggregation, composition, or association. All three are explained in detail.


1 Answers

The first one creates an object of the type Person, while the second one creates an object of the type Object. The first one allows you to add members to the prototype of Person.

You can put all the functions in the prototype instead of creating new functions for every instance:

function Person(name){
  this.name = name;
}

Person.prototype = {
  setName: function(val){
    this.name = val;
  },
  getName: function(){
    return this.name
  }
}
like image 114
Guffa Avatar answered Sep 21 '22 01:09

Guffa