构造函数继承主要适合解决什么问题,相比组合继承各有什么优缺点

2021-04-06 14:01发布

2条回答

构造函数继承

function Parent(name) {
  this.name = name;
}
function Child() {
  Parent.call(this, "妲己");
  //或者Parent.apply(this, ["妲己"]);
}
var Person = new Child();
console.log(Person.name); //妲己

优点:可以传参数

缺点:不能继承原型中的属性/方法


组合继承

function Parent (name) {
  this.name = name;
}
Parent.prototype.money = "500W"

function Child (name, age) {
  Parent.call(this, name);  
  this.age = age;
}
Child.prototype = new Parent();
var Person = new Child("妲己",18)
console.log(Person)    // 可以获取到妲己、18、500W

优点:可以传参数,可以继承原型中的属性/方法

缺点:Child中就有name属性,而new Parent()也有name属性。这只能说是有一点点小瑕疵,算不上缺点。

一周热门 更多>