一、继承
1、原型链继承
优点:
1.父类新增原型方法/原型属性,子类都能访问到
2.简单,易于实现缺点:
1.无法实现多类继承
2.来自原型对象的所有属性被所有实例共享
3.创建子类实例时,无法向父类构造函数传参
4.要想为子类原型增加属性和方法,必须要在Child.prototype = new Father() 之后执行,不能放到构造器中
//父类
function Parent(name, age) {
this.name = name;
this.age = age;
}
Parent.prototype.speak = function () {
console.log("父类的方法");
};
Parent.prototype.family = ["爸爸"];
//子类
function Child(name) {
this.name = name;
}
//技术关键点 把父类的实例对象给子类原型
Child.prototype = new Parent("父类");
Child.prototype.constructor = Child;
Child.prototype.walk = function () {};
var c = new Child("大儿子");
c.family
c.name //undefined
2、盗用构造函数
优点:
1.解决了原型链继承中子类实例共享父类引用属性的问题
2.创建子类实例时,可以向父类传递参数
3.可以实现多继承(call多个父类对象)
缺点:
1.实例并不是父类的实例,只是子类的实例
2.只能继承父类的实例属性和方法,不能继承原型属性和方法
3.无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
function Parent() {
this.family = ["爸爸"];
}
Parent.prototype.speak = function () {
console.log("父类原型的方法");
};
function Child() {
Parent.call(this);
}
var c = new Child();
c.family.push("妈妈");
console.log(c);//可以访问
c.speak();//访问不到
function Parent(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
Parent.prototype.speak = function () {
console.log("父类的方法");
};
//子类;
function Child(name, age, sex) {
Parent.call(this, name, age);
this.sex = sex;
}
var c = new Child("父类", 50);
3、组合方式 原型链 + 盗用构造函数
优点:
1.可以继承实例属性/方法,也可以继承原型属性/方法
2.不存在引用属性共享问题
3.可传参
4.函数可复用
缺点:
调用了两次父类构造函数,生成了两份实例
//父类
function Parent(name, age) {
this.name = name;
this.age = age;
}
Parent.prototype.speak = function () {
console.log("父类的方法");
};
//子类
function Child(name, age) {
Parent.call(this, name, age);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var c = new Child("父类", 50);
4、组合方式优化
//父类
function Parent(name, age) {
this.name = name;
this.age = age;
}
Parent.prototype.speak = function () {
console.log("父类的方法");
};
//子类
function Child(name, age) {
Parent.call(this, name, age);
}
// Child.prototype = new Parent();
Child.prototype = Object.create(Parent.prototype); //Parent上的属性与方法
Child.prototype.constructor = Child;
var c = new Child("父类", 50);
5、ES6继承
// 父类;
class Parent {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(this.name);
}
}
//子类继承
class Child extends Parent {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;//写在super之后
}
cry() {
console.log(this.sex);
}
}
var c = new Child("小头爸爸", 50, "女");
console.log(c);
c.cry();//可以访问
c.speak();//可以访问父类的方法
super的用法用于继承父类的this和他()里面是父类的参数
在构造函数中使用时,super关键字将单独出现,并且必须在使用this关键字之前使用
探索JavaScript继承方式:原型链、构造函数盗用与ES6类
701

被折叠的 条评论
为什么被折叠?



