Javascript

js 多重继承

2017-11-12  本文已影响0人  ccw1078

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

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 对象 扩展并覆盖子对象中的冲突属性;

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();
上一篇 下一篇

猜你喜欢

热点阅读