子类继承父类的方法(多重继承)

function M1() {
this.hello = 'hello';
}
M1.prototype.sayHello=function(){
console.log("sayHello");
}

function M2() {
this.world = 'world';
}
M2.prototype.sayWorld=function(){
console.log("sayWorld");
}

function S() {
M1.call(this);
M2.call(this);
}

@*
S.prototype=new M1();
S.prototype=new M2();

var o=new S();
console.log(o.hello);//hello
console.log(o.world);//world
o.sayHello();//sayHello
o.sayWorld();//TypeError: o.sayHello is not a function 不允许一个对象同时继承多个对象
*@


//更改方案如下:
S.prototype=new M1();
Object.assign(S.prototype, M2.prototype);//实现个对象同时继承多个对象
S.prototype.constructor=S;

var o=new S();
console.log(o.hello);//hello
console.log(o.world);//world
o.sayHello();//sayHello
o.sayWorld();//sayWorld

posted on 2017-10-12 18:02  龟和兔子赛跑  阅读(206)  评论(0)    收藏  举报

导航