如何全面剖析JavaScript的继承机制?

更新于
2026-10-02 17:54:04
1阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1644个文字,预计阅读时间需要7分钟。

在ES6之前,JavaScript并没有像现在这样的继承机制。ES5引入了函数式继承和类式继承。

javascript// 声明父类function Father() { this.fatherVal='father';}

// 为父类添加共有方法Father.prototype.getFatherValue=function() { return this.fatherVal;};

ES6之前,JavaScript并没有继承这一现有的机制。

ES5的继承方式

类式继承

//声明父类 function Father(){ this.fatherVal = 'father'; } //为父类添加共有方法 Father.prototype.getFatherValue = function(){ return this.fatherVal; } //声明子类 function Child(){ this.childVal = 'child'; } //继承父类 Child.prototype = new Father(); //为子类添加共有方法 Child.prototype.getChildValue = function(){ return this.childVal; }

子类的prototype被赋予父类的实例,新创建的对象复制了父类的构造函数内的属性和方法并且将原型_proto_指向了父类的原型对象,这样就拥有了父类的原型对象上的属性和方法与父类构造函数中复制的属性和方法。

阅读全文

本文共计1644个文字,预计阅读时间需要7分钟。

在ES6之前,JavaScript并没有像现在这样的继承机制。ES5引入了函数式继承和类式继承。

javascript// 声明父类function Father() { this.fatherVal='father';}

// 为父类添加共有方法Father.prototype.getFatherValue=function() { return this.fatherVal;};

ES6之前,JavaScript并没有继承这一现有的机制。

ES5的继承方式

类式继承

//声明父类 function Father(){ this.fatherVal = 'father'; } //为父类添加共有方法 Father.prototype.getFatherValue = function(){ return this.fatherVal; } //声明子类 function Child(){ this.childVal = 'child'; } //继承父类 Child.prototype = new Father(); //为子类添加共有方法 Child.prototype.getChildValue = function(){ return this.childVal; }

子类的prototype被赋予父类的实例,新创建的对象复制了父类的构造函数内的属性和方法并且将原型_proto_指向了父类的原型对象,这样就拥有了父类的原型对象上的属性和方法与父类构造函数中复制的属性和方法。

阅读全文