js继承对象的方式

1.原型链继承

原型链继承是JavaScript中最常用的继承方式之一,它通过将子类的原型指向父类的实例来实现继承。这种方式的缺点是父类的引用类型属性会被所有子类实例共享,容易造成属性污染。

function Parent() {
  this.name = 'parent';
}

Parent.prototype.sayName = function() {
  console.log(this.name);
}

function Child() {
  this.name = 'child';
}

Child.prototype = new Parent();

var child = new Child();
child.sayName(); // 输出 'child'

2.借用构造函数继承

借用构造函数继承是通过在子类的构造函数中调用父类的构造函数来实现继承。这种方式的缺点是不能继承父类原型链上的属性和方法。

function Parent() {
  this.name = 'parent';
}

function Child() {
  Parent.call(this);
  this.name = 'child';
}

var child = new Child();
console.log(child.name); // 输出 'child'

3.组合继承

组合继承是将原型链继承和借用构造函数继承结合起来的一种继承方式。这种方式的优点是既能继承父类原型链上的属性和方法,又能避免父类引用类型属性被所有子类实例共享的问题。

function Parent() {
  this.name = 'parent';
}

Parent.prototype.sayName = function() {
  console.log(this.name);
}

function Child() {
  Parent.call(this);
  this.name = 'child';
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child = new Child();
child.sayName(); // 输出 'child'

3.原型式继承

原型式继承是通过创建一个临时构造函数,将一个对象作为该构造函数的原型,然后返回该构造函数的实例来实现继承。这种方式的缺点是容易造成属性污染。

function object(obj) {
  function F() {}
  F.prototype = obj;
  return new F();
}

var parent = {
  name: 'parent',
  sayName: function() {
    console.log(this.name);
  }
};

var child = object(parent);
child.name = 'child';
child.sayName(); // 输出 'child'

5.寄生式继承

寄生式继承是在原型式继承的基础上,增加了一个包装函数,用于对继承对象进行扩展。这种方式的缺点是容易造成属性污染。

function createAnother(obj) {
  var clone = Object.create(obj);
  clone.sayName = function() {
    console.log(this.name);
  };
  return clone;
}

var parent = {
  name: 'parent'
};

var child = createAnother(parent);
child.name = 'child';
child.sayName(); // 输出 'child'

寄生组合式继承
盗用构造函数继承 + 原型式继承

function Super(){ this.a=[1,2] }
Super.prototype.say = function(){ console.log(‘hhh’) }
function Sub(){
    Super.call(this)
    this b=2
}

Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub

const test = new Sub()

优点:集合了【原型式继承】和【盗用构造函数继承】的优点,效率比【组合继承】更高。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值