寄生组合式继承的实现

/**

*

* @param {*} SubType 子类

* @param {*} superType 父类

*/

function inheritPrototype(SubType,superType){

superType.prototype = Object.create(superType.prototype)

Object.defineProperties(superType.prototype,'constructor',{

enumerable:false,

configurable:true,

writable:true,

        value:SubType

})

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 JavaScript 中,原型继承可以通过以下几种方实现: 1. 构造函数继承:通过在子类构造函数中调用父类构造函数来实现属性继承。在子类构造函数中调用父类构造函数可以使用 call 或 apply 方法实现。 ```js function Parent(name) { this.name = name; } function Child(name, age) { Parent.call(this, name); this.age = age; } ``` 2. 原型链继承:通过将子类的原型对象指向父类的实例来实现原型继承。 ```js function Parent() {} Parent.prototype.sayHello = function() { console.log('Hello'); } function Child() {} Child.prototype = new Parent(); Child.prototype.constructor = Child; ``` 3. 组合继承:通过将构造函数继承和原型链继承结合起来,既可以继承属性,也可以继承方法。 ```js function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); } function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; ``` 4. 原型继承:通过 Object.create 方法创建一个新对象,并将该对象的原型指向一个已有的对象,从而实现继承。 ```js var parent = { name: 'parent', sayHello: function() { console.log('Hello'); } }; var child = Object.create(parent); child.age = 18; ``` 5. 寄生继承:通过在原型继承的基础上,增强新对象,从而实现继承。 ```js function createChild(parent) { var child = Object.create(parent); child.sayName = function() { console.log(this.name); } return child; } var parent = { name: 'parent' }; var child = createChild(parent); child.sayName(); ``` 6. 寄生组合继承:通过在组合继承的基础上,优化父类实例的创建,从而实现继承。 ```js function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); } function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值