3

In the following code a constructor function, an object instance, and two examples of changing a functions prototype. What is the difference between these two methods? As far as I can work out the second method will update the object instance even if it is after the declaration of that instance, whereas the other will not. Is this the only difference?

function Foo(name, color) {
  this.name = name;
  this.color = color;
}

var bar = new Foo('name', 'color');

First method:

Foo.prototype = {age: 6};

Second method:

Foo.prototype.age = 4;`
alex
  • 5,467
  • 4
  • 33
  • 43

1 Answers1

1
Foo.prototype = {age: 6};

First method is going to override constructor and ____proto____ link ,if you were using inheritance not a good approach becuase you will destroy the proto links and prototype chain

Its better to use

Foo.prototype.age = 4;`

In this way you are just only adding a property all the prototype chains will remail intact

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • 1
    Would you only use `Foo.prototype = {age: 6};` specifically to override the inheritance chain? – alex Jun 26 '16 at 09:04
  • 1
    If you have simple function , lets say function Person(){} You could do Foo.prototype = {age: 6}; , it is going to work absolutely fine just add the constructor – Piyush.kapoor Jun 26 '16 at 09:07
  • 1
    Normally if see libraries they basically use Foo.protytype.someFunction = function (){} and donot assign a new object to the protoype – Piyush.kapoor Jun 26 '16 at 09:09