4

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

bill fred
  • 139
  • 2
  • 6
  • 1
    tldr; returning from a ctor returns *that* value (in this case, an object created *inside* the ctor). Semantically, a ctor that does not have any value explicitly returned can be thought of as having an implicit `return this;`. The primary resulting-object difference in the question is thus between an object *created* view `new` (eg. `this` is ctor).. and objects that are created via literals. – user2864740 Jan 01 '18 at 22:23
  • This question is not a duplicate of the one it is marked a duplicate of!!! – doubleOrt Jan 03 '18 at 17:06

1 Answers1

1

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 ()
Paul
  • 35,689
  • 11
  • 93
  • 122
  • You should have added a more complete answer. E.g what if I were to say `obj.getName = function() { return this.name};` ? To the naked eye, it would look as if it were the exact same thing as the example you provided. – doubleOrt Jan 03 '18 at 17:07