@@ -14,6 +14,11 @@ differences between the two models.
1414
1515The first major difference is that inheritance in JavaScript is done by using so
1616called * prototype chains* .
17+
18+ > ** Note:** Simply using ` Bar.prototype = Foo.prototype ` will result in both objects
19+ > sharing the ** same** prototype. Therefore, changes to either object its prototype
20+ > will affect the other its prototype as well, which in most cases is not the
21+ > desired effect.
1722
1823 function Foo() {
1924 this.value = 42;
@@ -24,16 +29,23 @@ called *prototype chains*.
2429
2530 function Bar() {}
2631
27- // Set Bar's prototype to the prototype object of Foo
28- Bar.prototype = Foo.prototype;
32+ // Set Bar's prototype to a new instance of Foo
33+ Bar.prototype = new Foo();
34+ Bar.prototype.foo = 'Hello World';
35+
36+ // Make sure to list Bar as the actual constructor
37+ Bar.prototype.constructor = Bar;
2938
3039 var test = new Bar() // create a new bar instance
3140
3241 // The resulting prototype chain
33- Object.prototype: {toString: ... /* etc. */};
34- Foo.prototype: {method: ...};
35- Bar.prototype: Foo.prototype
36- Bar.method()
42+ test [instance of Bar]
43+ Bar.prototype [instance of Foo]
44+ { foo: 'Hello World' }
45+ Foo.prototype
46+ {method: ...};
47+ Object.prototype
48+ {toString: ... /* etc. */};
3749
3850In the above, the object ` test ` will inherit from both ` Bar.prototype ` and
3951` Foo.prototype ` ; hence, it will have access to the function ` method ` that was
@@ -64,31 +76,8 @@ primitives will simply get ignored when assigned as a prototype.
6476 function Foo() {}
6577 Foo.prototype = 1; // no effect
6678
67- Assigning objects on the other hand will work, and allows for dynamic creation of
68- prototype chains.
69-
70- function Foo() {
71- this.value = 42;
72- }
73- Foo.prototype = {
74- method: function() {}
75- };
76-
77- function Bar() {}
78-
79- Bar.prototype = new Foo();
80- var boo = new Bar();
81-
82- // Resulting prototype chain
83- Object.prototype: {toString: ... /* etc. */};
84- Foo.prototype: {method: ...};
85- [Foo Instance]: {value: 42};
86- Bar.prototype: [Foo Instance]
87- Bar.method()
88-
89- Now ` Bar.prototype ` points to an * instance* of ` Foo ` ; thus, the property
90- ` value ` of that very instance is now on the prototype chain. And since ` Foo `
91- itself has a prototype, the chain goes on with that one afterwards.
79+ Assigning objects, as shown in the example above, will work, and allows for dynamic
80+ creation of prototype chains.
9281
9382### Performance
9483
0 commit comments