Question

I notice in MDN they said: "redefining the prototype is not recommended" and they gave an example of redefining the prototype and an example of how to better do it by appending to the existing prototype instead of redefining the prototype.

I especially wondered about this because of other cases like this where we need to redefine the prototype:

Cube.prototype = Object.create(....)
Manager.prototype = new Employee;

Is it that MDN is saying that you should not redefine the prototype for the situations like the example they gave (shown below) but it is in fact OK to redefine it for situations like I just mentioned above?

Here (paraphrased) is what they said on the MDN page:

//MDN says this is not the best way since it redefines the prototype

function MyObject(name, message) {
 this.name = name.toString();
 this.message = message.toString();
}
MyObject.prototype = {
 getName: function() {
  return this.name;
 },
 getMessage: function() {
  return this.message;
 }
};

//MDN says this is better to do it this way since this does not
//redefine the prototype:

function MyObject(name, message) {
 this.name = name.toString();
 this.message = message.toString();
}
MyObject.prototype.getName = function() {
 return this.name;
};
 MyObject.prototype.getMessage = function() {
return this.message;
};

My questions: is this correct and if so can you shed some under-the-hood details to answer why. Especially looking at the MDN example -- why is one way actually better than the other way?

One quick note: I love MDN and appreciate all the work on that site! My comments above are just a question so I can understand the rules of redefining the prototype and not in any way a criticism to what they said.

Was it helpful?

Solution

Here is the difference in the two approaches:

When you redefine the prototype, you are removing any properties that DID exist on the item and you are giving it a whole new set. Kind of a slash-and-burn approach.

On the other hand, when you add a new property, as shown in the second example, you are leaving anything that exists in place and simply adding that one property.

Extending, rather than overwriting, an object tends to be a bit more flexible and easier to debug, but it really comes down to a matter of style.

If you are are starting with a freshly constructed object, both approaches do exactly the same thing.

If you are starting with an existing object, the second form is the only one that makes sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top