Javascript constructor and Literal Confusion object

I recently met designers to create multiple objects with the same properties and methods.

Method 1:

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

And then you can create it like this:

var bob = new Person("bob");

What I would like to know, there is a difference between using the standard constructor method and just returning the object inside such a function:

Method 2:

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

I can still create multiple objects using the same function. I'm just a little confused about why you will use Method 1? Is it because I can extend the first method using the prototype property? Can I extend and create more methods using Method 2?

, , , ? ?

, .

,

+4
1

:

  function Person(name) { /* either of your approaches */}

  Person.prototype.getName = function() {
    return this.name; 
  }

1 , 2 , :

  new Person('Bob').getName ()
+1

Source: https://habr.com/ru/post/1691598/


All Articles