大多数前端开发者在面试的时候,是否是常常被问到 怎样实现JS中的继承?
, 其实实现继承的方式有多种。 原型链继承,构造函数继承,组合继承
等等。在此文中,咱们重点介绍 原型链的方式。前端
静态属性es6
class es6{
}
es6.staticAttr = '静态属性'
复制代码
静态方法面试
class es6{
static a(){
console.log('静态方法');
}
}
复制代码
公有属性或方法编程
class es6{
}
es6.prototype.publicFunc = () => {
console.log('公有方法');
}
复制代码
从文中咱们能够得出以下结论:bash
1. 类Duck经过prototye属性指向其原型(内存空间)
2. 实duck例经过__proto__属性指向原型
3. 原型prototype经过construcror指向类Duck
复制代码
所以实现继承,能够将类Duck的prototype指向被继承类(Animal)的实例(animal, 经过 new Animal建立):函数
Duck.prototype = new Animal;ui
继承所有属性和方法this
//定义基类
function Animal(){
this.name = 'Animal'; //私有属性
}
Animal.fn = 'fn'; //静态属性
Animal.prototyep.eat = function(){ //公有方法或属性
console.log('吃');
}
//定义子类
function Duck(){
this.type = 'Duck'; //私有属性
}
Duck.prototype = new Animal;
let duck = new Duck;
duck.eat(); // 打印: 吃
console.log(duck.name); // 打印: Animal
复制代码
只继承公有方法 有时候显然不想让子类继承父类的私有属性, 就像子类不可能跟父类使用同一个名字同样。这时能够这样实现继承:spa
方式一. Duck.prototype.__proto__ = Animal.prototype; //__proto__属性在object这节中有介绍
复制代码
function Animal(){
this.name = 'Animal'; //私有属性
}
Animal.prototyep.eat = function(){ //公有方法或属性
console.log('吃');
}
//定义子类
function Duck(){
this.type = 'Duck'; //私有属性
}
Duck.prototype.swim = function(){
console.log('游泳');
}
Duck.prototype.__proto__ = Animal.prototype; //只继承Animal的公有方法或者属性
let duck = new Duck;
duck.eat(); //打印: 吃, 在Duck的原型上找不到eat方法,就经过__proto_向上找到 Animal.prototype上的eat方法
duck.swim(); //打印: 游泳
console.log(duck.name); // 打印: undefined, 先会在Duck类上找name私有属性,并且Animal.prototype没有包含Animal类的私有属性
复制代码
方式二. Duck.prototype.__proto__ = Object.create(Animal.prototype);
复制代码
方式三. 对方式二的一种实现
function create(prototype){
function Fn(){} //没有任何私有属性
Fn.prototype = prototype;
return new Fn();
}
Duck.prototype.__proto__ = create(Animal.prototype);
复制代码
extends 关键字prototype
class Animal{
constructor(name){//私有属性
this.name = name;
}
static a(){ //静态方法
}
eat(){ //公有方法
console.log('吃');
}
}
class Duck extends Animal{
constructor(type){
super();
this.type = type;
}
swim(){
console.log('游泳');
}
}
复制代码
上述内容基本上说明了,js中原型链继承的基本原理。对于面向OOP编程。又前进了一大步。