JavaScript中的继承
构造函数继承(修改 this 指向)
缺点: 每实例一次就开辟一次空间,影响性能。
function Person(name, age) {
this.name = name;
this.age = age;
this.showName = function () {
return this.name;
};
}
//改变this指向
function Student(name, age) {
Person.call(this, name, age);
// Person.apply(this,arguments)
// Person.bind(this,name,age)()
}
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明
原型链继承
缺点: 不能实现多继承;每一个对象都共享一个属性。
function Person() {}
Person.prototype.name = "小明";
Person.prototype.age = 18;
Person.prototype.showName = function () {
return this.name;
};
// let xm = new Person();
// console.log(xm.showName());
// 原型链
function Student() {}
Student.prototype = new Person();
let xm = new Student();
console.log(xm);
混合原型链继承
缺点: 生成俩份实例。
function Person(name, age) {
// 实例属性
this.name = name;
this.age = age;
}
// 原型方法
Person.prototype.showName = function () {
return this.name;
};
function Student(name, age) {
Person.apply(this, arguments);
// Person.bind(this,name,age)()
}
Student.prototype = new Person();
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明
混合寄生继承
function Person(name, age) {
// 实例属性
this.name = name;
this.age = age;
}
// 原型方法
Person.prototype.showName = function () {
return this.name;
};
function Student(name, age) {
Person.apply(this, arguments);
}
for (key in Person.prototype) {
Student.prototype[key] = Person.prototype[key];
}
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明