总结

   行为委托认为对象之间是兄弟关系,互相委托,而不是子类和父类的关系。JavaScrip的[[]prototype]机制本质上就是行为委托。也就是说,我们可以选择在JavaScript中努力实现类机制,也可以拥抱更自然的[prototype]委托机制

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
// 面向对象风格
function Foo() {
this.me = who;
}

Foo.prototype.identify = function () {
return "I am " + this.me
}

function Bar(who) {
Foo.call(this, who);
}

Bar.prototype = Object.create(Foo.prototype);

Bar.prototype.speak = function () {
alert("hello," + this.identify() + '.')
}

var b1 = new Bar('b1');
var b2 = new Bar('b2');

console.log(b1.speak());
console.log(b2.speak());
// 对象关联风格

Foo={
init: function(who) {
this.me=who;
},
identify: function() {
return "I am" +this.me;
}
};

Bar=object.create(Foo);
Bar.speak=function() {
alert("hello," + this.identify() + '.')
};

var b1=object.create(Bar);
b1.init("b1");
var b2=object.create(Bar);
b2.init('b2');
b1.speak();
b2.speak();