美文网首页
前端面试js篇:javascript中实现继承的几种方式

前端面试js篇:javascript中实现继承的几种方式

作者: 5cc9c8608284 | 来源:发表于2024-03-17 11:20 被阅读0次

在 JavaScript 中,有以下几种方式可以实现继承:

  1. 原型链继承:
    原型链继承是通过将一个对象的实例作为另一个对象的原型来实现继承。这意味着子类的原型对象继承了父类的属性和方法。但是,原型链继承有一个缺点,即原型对象是共享的,子类对原型对象的修改会影响到所有子类的实例。
    示例代码如下:
function Parent() {
  this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello from Parent!');
}

function Child() {
  this.age = 10;
}

Child.prototype = new Parent();

var child = new Child();
console.log(child.name); // Output: Parent
child.sayHello(); // Output: Hello from Parent!
  1. 构造函数继承:
    构造函数继承是通过在子类构造函数内部调用父类构造函数来实现继承。这样子类实例只会继承父类构造函数中的属性,而不会继承父类原型对象中的属性和方法。
    示例代码如下:
function Parent() {
  this.name = 'Parent';
}

function Child() {
  Parent.call(this);
  this.age = 10;
}

var child = new Child();
console.log(child.name); // Output: Parent
  1. 组合继承:
    组合继承是将原型链继承和构造函数继承结合起来。通过调用父类构造函数时使用 call 方法,并将子类的原型对象设置为父类的实例,来同时继承父类构造函数中的属性和方法,并保持原型链的关系。
    示例代码如下:
function Parent() {
  this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello from Parent!');
}

function Child() {
  Parent.call(this);
  this.age = 10;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

var child = new Child();
console.log(child.name); // Output: Parent
child.sayHello(); // Output: Hello from Parent!
  1. ES6 的 class 继承:
    在 ES6 中,引入了 class 关键字来定义类,通过 extends 关键字来实现继承。class 继承简化了继承的过程,并提供了更清晰的语法来定义类和处理继承关系。
    示例代码如下:
class Parent {
  constructor() {
    this.name = 'Parent';
  }

  sayHello() {
    console.log('Hello from Parent!');
  }
}

class Child extends Parent {
  constructor() {
    super();
    this.age = 10;
  }
}

var child = new Child();
console.log(child.name); // Output: Parent
child.sayHello(); // Output: Hello from Parent!

以上是 JavaScript 中几种常见的继承实现方式。每种方式都有其特点和适用场景,根据实际情况选择合适的方式进行继承

相关文章

网友评论

      本文标题:前端面试js篇:javascript中实现继承的几种方式

      本文链接:https://www.haomeiwen.com/subject/ujvozdtx.html