1. 概念
- 让一个原本没有某个功能的对象(类),使用另一个对象(类)的功能
- 使用权限 的 授权
2. 面向对象中的继承
- 构造函数的原型 和 实例之间的关系
- 继承关系
3. 构造函数(类)与构造函数(类)之间的继承
- 改变this指向继承
//定义一个构造函数: function Speak(){ this.speak = function(){ console.log("这是一个:通话") } } //定义一个phone函数,同时继承上面函数的属性和方法: function Phone(){ Speak.call(this); } //new执行Phone函数: var p1 = new Phone; p1.speak(); //改变this指向继承: // 优点:简单、方便、易操作 // 缺点:只能继承构造函数内部的属性或方法,无法继承原型上的属性或方法
- 原型继承
- 方式1:对象直接复制,浅拷贝,修改新数据,会影响老数据(极大缺点)
function Parent(){} Parent.prototype.init = function(){ console.log("hahhaha") } function Child(){} //直接浅拷贝Parent的原型 Child.prototype = Parent.prototype; var c = new Child(); c.init()
- 方式2:切换成深拷贝:(缺点:比较消耗性能,没有充分利用原型的特点)
function Parent(){} Parent.prototype.init = function(){ console.log("hahhaha") } function Child(){} //深拷贝 for(var i in Parent.prototype){ Child.prototype[i] = Parent.prototype[i]; } var c = new Child(); c.init()
- 方式3:将子类的原型设置成父类的实例(有隐患,某些参数的处理会报错)
function Parent(){} Parent.prototype.init = function(){ console.log("hahhaha") } function Child(){} //将父类的实例设置为原型 Child.prototype = new Parent(); var c = new Child(); c.init()
function Parent(name){ this.name = name; this.init(); } Parent.prototype.init = function(){ var res = this.name.slice(0,3); console.log(res); } //必须给Parent传参,否则Parent会报错; Child.prototype = new Parent("admin"); function Child(n){ this.name = n; this.init(); } var c = new Child("root");
- 方式4:ES6提供的object.create方法
//Object.create方法: //创建对象,同时将创建的对象的隐式原型指向参数1的对象 var obj =Object.create(Parent.prototype)
function Parent(name){ this.name = name; this.init(); } Parent.prototype.init = function(){ var res = this.name.slice(0,3); console.log(res); } //,创建对象,同时将创建的对象的隐式原型指向参数1的对象 Child.prototype = Object.create(Parent.prototype); function Child(n){ this.name = n; this.init(); } var c = new Child("root");
- 混合继承
function Parent(n){ this.name = n; } Parent.prototype.show = function(){ console.log(this.name); } function Child(n){ Parent.call(this,n); } Child.prototype = Object.create(Parent.prototype); var c = new Parent("root"); c.show(); //使用this指向方法继承构造函数中的属性或方法 //使用原型继承,继承原型身上的属性或方法
- ES6的class继承
class Parent{ constructor(n){ this.name = n; } init(){ console.log(this.name) } }
//使用extends继承Parent的属性或方法 class Child extends Parent{ constructor(n){ super(n); } } var p = new Parent("admin"); p.init(); console.log(p); var c = new Child("root"); c.init(); console.log(c);
4. 继承的应用场景:
- 当有多个类,具有相同特点时,可以将共同点,抽象出一个公共类
- 具体的类,先从公共类的身上继承得到公共方法或属性,再自定义添加当前类的方法或属性