-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinheritance.js
74 lines (53 loc) · 1.47 KB
/
inheritance.js
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
/**
* 伪类
*/
var Mannal = function (name) {
this.name = name;
}
Mannal.prototype.get_name = function () {
return this.name; // 事实上 new 出来的对象可以直接访问它的属性,而不需要通过函数来桥接;
}
Mannal.prototype.says = function () {
return this.saying || '';
}
var Cat = function (name) {
this.name = name;
this.saying = 'meow';
}
// set Cat.prototype chain to Mannal.prototype
Cat.prototype = new Mannal();
Cat.prototype.get_name = function () {
return this.says() + ' ' + this.name + ' ' + this.says();
}
var myCat = new Cat('Guanfu Mao');
var myCat_another = new Cat('DuDu Mao');
// 原型链相同,指向同一个函数
console.log(myCat.says === myCat_another.says); // true
/**
* 函数化,用函数化的方式构造对象
*/
var mannal = function (spec) {
var that = {};
that.get_name = function () {
return spec.name;
}
that.says = function () {
return spec.saying || '';
}
return that;
}
var cat = function (spec) {
spec.saying = spec.saying || 'meow';
var that = mannal(spec);
// 调用父类的方法
var super_get_name = that.get_name;
that.get_name = function () {
// return that.says() + ' ' + spec.name + ' ' + that.says();
return super_get_name() + ', get_name proxy by super_get_name'
}
return that;
}
var _myCat = cat({name: 'Guanfu Mao'})
var _myCat_another = cat({name: 'DuDu Mao'});
// 每个对象的属性和方法都是私有化的
console.log(_myCat.says === _myCat_another.says); // false