@@ -14,6 +14,11 @@ differences between the two models.
14
14
15
15
The first major difference is that inheritance in JavaScript is done by using so
16
16
called * 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.
17
22
18
23
function Foo() {
19
24
this.value = 42;
@@ -24,16 +29,23 @@ called *prototype chains*.
24
29
25
30
function Bar() {}
26
31
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;
29
38
30
39
var test = new Bar() // create a new bar instance
31
40
32
41
// 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. */};
37
49
38
50
In the above, the object ` test ` will inherit from both ` Bar.prototype ` and
39
51
` 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.
64
76
function Foo() {}
65
77
Foo.prototype = 1; // no effect
66
78
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.
92
81
93
82
### Performance
94
83
0 commit comments