新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

js实现继承的有什么方法,js 继承方式

发布时间:2023-08-07 07:57:26

js实现继承的有甚么方法

在 JavaScript 中,有几种方法可以实现继承:
1. 原型链继承:通过将子类的原型对象设置为父类的一个实例来实现继承。这模样类就能够继承父类的属性和方法。例如:
```javascript
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
```
2. 构造函数继承:通过在子类构造函数中调用父类构造函数来实现继承。这模样类就能够继承父类的属性,并且子类的每一个实例都有自己的属性的副本。但是,子类没法继承父类的原型上的方法。例如:
```javascript
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 报错:child.sayHello is not a function
```
3. 组合继承:通过同时使用原型链继承和构造函数继承来实现继承。这模样类就能够继承父类的属性和方法,并且子类的每一个实例都有自己的属性的副本。例如:
```javascript
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
```
4. 寄生组合继承:通过创建一个中间函数来实现继承,并且在该中间函数中使用 Object.create() 方法来创建子类原型的副本,然后再将该副本设置为子类的原型。这样可以免调用父类构造函数两次。例如:
```javascript
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
```
这些都是常见的实现继承的方法,每种方法都有自己的优势和劣势,可以根据具体情况选择适合的方法。