[js] prototype chain
最近在看本书 pro javascript,受益匪浅。
在看closure这章的时候,作者推荐 http://jibbering.com/faq/faq_notes/closures.html 这篇文章。
很不错的一篇文章,很深入,所以看得很慢。看到有段代码有点意思,是关于prototype chain的:
1
/* A "constructor" function for creating objects of a -
2
MyObject1 - type.
3
*/
4
function MyObject1(formalParameter){
5
/* Give the constructed object a property called - testNumber - and
6
assign it the value passed to the constructor as its first
7
argument:-
8
*/
9
this.testNumber = formalParameter;
10
}
11
12
/* A "constructor" function for creating objects of a -
13
MyObject2 - type:-
14
*/
15
function MyObject2(formalParameter){
16
/* Give the constructed object a property called - testString -
17
and assign it the value passed to the constructor as its first
18
argument:-
19
*/
20
this.testString = formalParameter;
21
}
22
23
/* The next operation replaces the default prototype associated with
24
all MyObject2 instances with an instance of MyObject1, passing the
25
argument - 8 - to the MyObject1 constructor so that its -
26
testNumber - property will be set to that value:-
27
*/
28
MyObject2.prototype = new MyObject1( 8 );
29
30
/* Finally, create an instance of - MyObject2 - and assign a reference
31
to that object to the variable - objectRef - passing a string as the
32
first argument for the constructor:-
33
*/
34
35
var objectRef = new MyObject2( "String_Value" );
36
/* A "constructor" function for creating objects of a -2
MyObject1 - type.3
*/4
function MyObject1(formalParameter){5
/* Give the constructed object a property called - testNumber - and6
assign it the value passed to the constructor as its first7
argument:-8
*/9
this.testNumber = formalParameter;10
}11

12
/* A "constructor" function for creating objects of a -13
MyObject2 - type:-14
*/15
function MyObject2(formalParameter){16
/* Give the constructed object a property called - testString -17
and assign it the value passed to the constructor as its first18
argument:-19
*/20
this.testString = formalParameter;21
}22

23
/* The next operation replaces the default prototype associated with24
all MyObject2 instances with an instance of MyObject1, passing the25
argument - 8 - to the MyObject1 constructor so that its -26
testNumber - property will be set to that value:-27
*/28
MyObject2.prototype = new MyObject1( 8 );29

30
/* Finally, create an instance of - MyObject2 - and assign a reference31
to that object to the variable - objectRef - passing a string as the32
first argument for the constructor:-33
*/34

35
var objectRef = new MyObject2( "String_Value" );36



浙公网安备 33010602011771号