user2913184 user2913184 - 6 months ago 16
Javascript Question

difference between prototype being assigned an object literal vs function

I found this article on the web which is confusing me a lot.

http://jonathancreamer.com/object-literals-and-prototypes-in-javascript/

When I run following code

case2:
Pizza.prototype = {
divvyUp: function () {
return this.type + " pizza which has " + this.slices +" slices";
}
};

Versus case1:

Pizza.prototype.divvyUp = function () {
return this.type + " pizza which has " + this.slices +" slices";
};


The conundrum is that though Pizza.prototype.constructor in case1: is the constructor function and Pizza.prototype.constrcutor in case2: is object() function and case2: decouples the inheritance chain. But then why when I execute
sausagePizza.divvyUp() for both the cases i get the same result. However when case2: is decoupling the inheritance chain and not referencing to Pizza() constructor any more then why do I get the result for case2 similar to case1

Answer

The former will replace the entire prototype with an object containing a single function - divvyUp.

The latter will modify the existing prototype, ADDING (or replacing) the function divvyUp.

Try

console.log(Pizza.prototype);

after each and have a looksie.