forked from SimplyWenjing/SimplyWenjing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.html
113 lines (101 loc) · 2.3 KB
/
object.html
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>对象和继承</title>
</head>
<body>
<script type="text/javascript">
//原生模式
function Person () {}
Person.prototype = {
constructor: Person,
name: "vicky",
age: 24,
job: "student",
sayName: function (){
console.log(this.name);
}
}
var friend = new Person();
friend.sayName();
//原型链实现继承
function SuperType () {
this.value = "super";
this.array = [1,2,3];
}
SuperType.prototype.getSuperValue = function () {
return this.value;
};
function SubType () {
this.subValue = "sub";
}
SubType.prototype = new SuperType ();//继承父类
SubType.prototype.getSubValue = function () {
return this.subValue;
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.array.push(4);
// console.log(instance1.array);
// console.log(instance2.array);
// console.log(instance1.getSubValue());
// console.log(instance1.getSuperValue());
//借用构造函数实现继承
function Father () {
this.array = [1,2,3];
}
function Son () {
Father.call(this);
}
var instance = new Son();
instance.array.push(5);
var instance3 = new Son();
// console.log(instance.array);//[1,2,3,5]
// console.log(instance3.array);//[1,2,3]
//组合继承
function Super (name) {
this.name = name;
this.array = [1,2,3];
}
Super.prototype.sayName = function () {
console.log(this.name);
};
function Sub (name,age) {
Super.call(this,name);
this.age = age;
}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub();
Sub.prototype.sayAge = function () {
console.log(this.age);
};
var a = new Sub("vicky",20);
a.array.pop(1);
a.sayName();
a.sayAge();
var b = new Sub("jay",37);
console.log(b.array);
console.log(a.array);
function DOG(name){
this.name = name;
this.species = '犬科';
}
var dogA = new DOG('大毛');
var dogB = new DOG('二毛');
dogA.species = '猫科';
//alert(dogA.species); // 显示"犬科",不受dogA的影响
var Chinese = {
nation:'中国'
};
function object (o) {
function F() {}
F.prototype = o;
return new F();
}
var Student = object(Chinese);
Student.job = "xuesheng";
alert(Student.nation);
</script>
</body>
</html>