Search code examples
javascriptobjectconstructorprototype

Javascript Constructor vs Object Literal Confusion


I recently came across constructors for creating multiple objects with the same properties and methods.

Method 1:

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

And then you can instantiate it like so:

var bob = new Person("bob");

What i would like to know is there a difference between using the standard constructor method and just returning an object inside a function like so:

Method 2:

function Person(name) {
  var obj = {
    name:  name,
  };
  return obj;
}

I am still able to create multiple objects using the same function. I am just slightly confused on why you would use 'Method 1'? Is it because i can extend the first method using the prototype property? Am i able to extend and create more methods using 'Method 2'?

Am i right in thinking this is why you use constructors because they are more flexible and can be added to and modified whereas the Object literal type inside a function cannot? Also what other benefits does it bring?

Sorry if this is a silly question.

Thanks, any information would be nice


Solution

  • Consider:

      function Person(name) { /* either of your approaches */}
    
      Person.prototype.getName = function() {
        return this.name; 
      }
    

    Method 1 will work as expected, method 2 will not, if you call:

      new Person('Bob').getName ()