在ES5和ES6中实现继承的方法

在ES5中,实现继承的方法主要有以下几种:

1、原型链继承:

原型链继承是通过将子类的原型对象指向父类的实例来实现继承。这种方式的缺点是子类实例共享父类实例的属性和方法。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
}
function Child() {
  this.age = 10;
}
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 输出:Hello, Parent

2、构造函数继承:

构造函数继承通过在子类构造函数中调用父类构造函数来实现继承,可以继承父类的属性。但是无法继承父类的原型上的方法。

function Parent(name) {
  this.name = name;
}
function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}
var child = new Child('Alice', 10);
console.log(child.name); // 输出:Alice

3、组合继承:

组合继承是将原型链继承和构造函数继承结合起来使用的方式,既继承了父类的属性和方法,又不共享父类实例的属性和方法。

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
}
function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child('Alice', 10);
child.sayHello(); // 输出:Hello, Alice

4、原型式继承:

原型式继承使用一个中间对象作为父类,通过浅拷贝的方式来实现继承。

function createObject(obj) {	//定义一个函数createObject,接受一个参数obj,表示要继承的对象。
  function F() {}
  F.prototype = obj;	//将F的原型对象设置为obj
  return new F();
}
var parent = {
  name: 'Parent',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
}
var child = createObject(parent);
child.name = 'Child';
child.sayHello(); // 输出:Hello, Child

在ES6中,实现继承的方法有以下几种:

1、class继承:

ES6引入了class的概念,可以使用class关键字来定义类。通过extends关键字来实现继承,子类继承了父类的属性和方法。

class Parent {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log('Hello, ' + this.name);
  }
}
class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
}
let child = new Child('Alice', 10);
child.sayHello(); // 输出:Hello, Alice

2、Object.create()方法:

Object.create()方法可以创建一个新对象,并将该对象的原型指向指定的对象。通过这种方式可以实现对象的继承。

let parent = {
  name: 'Parent',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};
let child = Object.create(parent);
child.name = 'Child';
child.sayHello(); // 输出:Hello, Child

3、Object.setPrototypeOf()方法:

Object.setPrototypeOf()方法可以将一个对象的原型指向另一个对象,从而实现对象的继承。

let parent = {
  name: 'Parent',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};
let child = {
  age: 10
};
Object.setPrototypeOf(child, parent);
child.sayHello(); // 输出:Hello, Parent

4、扩展运算符:

通过扩展运算符(…)可以将一个对象的属性和方法复制到另一个对象上,从而实现对象的继承。

let parent = {
  name: 'Parent',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};
let child = {
  age: 10,
  ...parent
};
child.sayHello(); // 输出:Hello, Parent
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值