借用构造函数继承

基本概念

借用构造函数(constructor stealing)进行继承的基本思想就是:在子类型构造函数的内部调用超类型构造函数

那么,如何调用?函数只不过是在特定环境中执行代码的对象,因此通过使用apply()和call()方法也可以在(将来)新创建的对象上执行构造函数。

示例代码

function SuperType() {
    this.number = [1, 2, 3];
}

function SubType() {
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.number.push(4);
instance1.number;  // "1,2,3,4"

var instance2 = new SubType();
instance2.number;  // "1,2,3"
 

构造函数继承的优势:可以传递参数

function SuperType(name) {
    this.name = name;
}

function SubType() {
    Super.call(this, "MirrorAvatar");
    this.age = 3;
}

var instance = new SuperType();

instance.name;  //MirrorAvatar
instance.age;  //3
 

借用构造函数继承的问题

  1. 方法都在构造函数中定义,函数无复用性;
  2. 在超类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。

以上,构造函数的技术很少单独使用。

原型链继承(Prototype Inheritance)在JavaScript中是通过创建一个新对象并让它引用另一个对象的原型来实现的。例如: ```javascript function Parent() {} Parent.prototype.method = function() { console.log('Parent method'); }; let child = new Parent(); child.method(); // 输出: "Parent method" ``` **借用构造函数继承**(Constructo r Chaining)利用已有构造函数作为父类,通过`new`关键字传递给子类实例化过程,间接实现继承: ```javascript function Parent() { this.parentProp = 'parent'; } function Child() { Parent.call(this); // 借用父类构造函数 this.childProp = 'child'; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; let childInstance = new Child(); console.log(childInstance.parentProp); // 输出: "parent" console.log(childInstance.childProp); // 输出: "child" ``` **组合式继承**(Mix-in or Prototype Mixing)结合原型链和构造函数继承,允许从多个源继承属性和方法: ```javascript function Mixin(target) { for (let prop in Mixin.prototype) { target[prop] = Mixin.prototype[prop]; } } function Parent() { this.parentProp = 'parent'; } Mixin(Parent.prototype); let child = new Parent(); console.log(child.parentProp); // 输出: "parent" ``` **ES6的class类继承**(Class-based Inheritance)使用`extends`关键字实现: ```javascript class Parent { constructor() { this.parentProp = 'parent'; } parentMethod() { console.log('Parent method'); } } class Child extends Parent { constructor() { super(); this.childProp = 'child'; } childMethod() { console.log('Child method'); } } let childInstance = new Child(); childInstance.parentMethod(); // 输出: "Parent method" childInstance.childMethod(); // 输出: "Child method" ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值