Differences in JavaScript OO methodology

javascript

Solution

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
  }
}

Problem

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?

Original source