2

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

user2913184
  • 590
  • 10
  • 33
  • The `.constructor` property that is implicitly added to the prototype object does have nothing to do with the inheritance chain. It's just a property [without any significance](https://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor-property) – Bergi May 30 '15 at 20:01

1 Answers1

2

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.

Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • when I write console.log(Pizza,prototype); in both cases the answer is [object Object] but when I write Pizza.prototype.constructor (case:1 gives me back the entire Pizza() constructor function and case2: hands me over function Object(){ [native code] }. Still confused. – user2913184 May 31 '15 at 00:10
  • Seeing `[object Object]` means that whatever you are logging has been converted to a string somehow... – Alex McMillan May 31 '15 at 00:27
  • Are you sure you've got your cases around the right way? Replacing `xxx.prototype` with an object literal should make `xxx.prototype.constructor === Object()`, while modifying the existing one should leave it as is, which is the exact opposite of what you're describing. – Alex McMillan May 31 '15 at 00:55
  • Glad I could help :) – Alex McMillan May 31 '15 at 01:17