forked from hehos/javascriptAdvanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParasiticCombinationInheritanceExample02.htm
More file actions
executable file
·77 lines (64 loc) · 2.52 KB
/
Copy pathParasiticCombinationInheritanceExample02.htm
File metadata and controls
executable file
·77 lines (64 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html>
<head>
<title>Parasitic Combination Inheritance Example</title>
<script type="text/javascript">
//使用更具面向对象封装的方式 改写寄生组合式继承
function object(o){
function F(){}
F.prototype = o;
return new F();
}
//
function inheritPrototype(subType, superType){
var prototype = object(superType.prototype); //创建 原型object
prototype.constructor = subType; //增强 object
subType.prototype = prototype; //指定 object
}
// function inheritPrototype(subType, superType){
// superType.prototype.constructor = subType; //augment object
// subType.prototype = superType.prototype; //assign object
// }
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
if(typeof this.sayName != "function" ) {
SuperType.prototype.sayName = function(){
alert(this.name);
};
}
}
function SubType(name, age){
// alert("in subType");
SuperType.call(this, name);
this.age = age;
if(typeof this.sayAge != "function") {
SubType.prototype.sayAge = function(){
alert(this.age);
};
}
}
// SubType.prototype.testtt = function() {
// alert("测试原型对象被重写前的函数调用");
// }
//执行该函数后SubType.prototype将指向新的原型对象,上面的testtt方法将不能够调用
inheritPrototype(SubType, SuperType);
// alert("prototype reset finish");
var instance1 = new SubType("Nicholas", 29);
// alert(instance1.constructor == SubType);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
var instance2 = new SubType("Greg", 27);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"Greg";
instance2.sayAge(); //27
// var instance3 = new SuperType();
// alert(instance3 instanceof SuperType);
// alert(instance3.constructor == SuperType);
</script>
</head>
<body>
</body>
</html>