js多重继承

方法一:克隆一个A对象,再将 B 对象的属性混入,适用于 A/B 的属性不冲突的场景;

1
2
3
4
5
6
7
8
9
10
function mixInto(object, mixIn){
forEachIn(mixIn, function(name, value){
object[name] = value;
});
};

var SmallDetailedItem = clone(DetailedItem);
mixInto(SmallDetailedItem, SmallItem);

var deadMouse = SmallDetailedItem.create("Fred the mouse", "he is dead");

方法二:用 A 对象扩展一个子对象,再用 B 对象 扩展并覆盖子对象中的冲突属性;

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
var Monster = Item.extend({
construct: function(name, dangerous){
Item.construct.call(this, name);
this.dangerous = dangerous;
},
kick: function(){
if (this.dangerous){
alert(this.name + " bites your head off");
}
else{
alert(this.name + " squeaks and runs away");
}
}
});

var DetailedMonster = DetailedItem.extend({
construct: function(name, description, dangerous){
DetailedItem.construct.call(this, name, dangerous);
Monster.construct.call(this, name, dangerous);
},
kick: Monster.kick
});

var giantSloth = DetailedMonster.create(
"the giant sloth",
"it is quietly hanging from a tree, munching leaves",
false);

giantSloth.kick();

js多重继承
https://ccw1078.github.io/2017/11/12/js 多重继承/
作者
ccw
发布于
2017年11月12日
许可协议