原型链继承
function Parent() {
this.name = "tom";
this.info = {
age: 18,
sex: "男",
};
}
Parent.prototype.getInfo = function () {
console.log(this.info);
};
function Child() {
}
// 创建父类的实例并赋值给子类的prototype,Child.prototype.construtor也一同被重写
Child.prototype = new Parent();
// 重写Child.prototype的constructor属性,指向自己的构造函数
Child.prototype.constructor = Child
let instance = new Child();
let instance1 = new Child();
instance.getInfo(); // { age: 18, sex: '男' }
instance.name = "jerry";
console.log(instance.name, instance1.name); // jerry tom
instance.info.age = 19;
// 引用类型
console.log(instance.info, instance1.info); // { age: 19, sex: '男' } { age: 19, sex: '男' }
缺点:
- 当原型链中包含引用类型值的原型时,该引用类型值会被所有实例共享
- 在创建子类时,不能想父类的构造函数传递参数
构造函数继承
function Parent(name) {
this.name = name;
this.info = {
age: 18,
sex: "男",
};
}
Parent.prototype.getInfo = function () {
console.log(this.info);
};
function Child(name) {
Parent.call(this, name);
}
// 可以向父类的构造函数传递参数
let instance1 = new Child("instance1"