js 多重继承

作者: ccw1078 | 来源:发表于2017-11-12 16:46 被阅读0次

方法一:克隆一个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();

相关文章

网友评论

    本文标题:js 多重继承

    本文链接:https://www.haomeiwen.com/subject/msqomxtx.html