如何在javascript中扩展现有的构造函数? [英] How to extend existing constructor function in javascript?

查看:46
本文介绍了如何在javascript中扩展现有的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我具有以下对象函数:

Let's suppose that I have the following object function:

function A(options){
 ...
}

然后,我想创建一个继承A原型的新函数(B).这些是我要寻找的条件:

Then I want to create a new function (B) that inherits A's prototype. These are the conditions I'm looking for:

  • B的原型,如果被修改,则不应修改A的
  • 当调用B函数作为构造函数时,应使用相应的选项来调用A的构造函数.

B应该看起来像这样:

B should look like this:

函数B(aOptions,bOptions){...}

function B(aOptions, bOptions){ ... }

var b = new B({}, {})

推荐答案

只需使用 this

function B(aOptions, bOptions) {
  A.call(this, aOptions);

  // do stuff with bOptions here...
}

现在要设置原型

B.prototype = Object.create(A.prototype, {
  constructor: {
    value: B
  }
});

现在B将具有A的原型方法.

Now B will have the prototype methods from A.

B的原型中添加的任何新方法将应用于A的原型

Any new methods added to B's prototype will not be available to A's prototype

还有其他一些调整也可以使您的生活更轻松.

There's a couple other tweaks that can make your life easier too.

function A(options) {

  // make `new` optional
  if (!(this instanceof A)) {
    return new A(options);
  }

  // do stuff with options here...
}

对B做同样的事情

function B(aOptions, bOptions) {

  // make `new` optional
  if (!(this instanceof B)) {
    return new B(aOptions, bOptions);
  }

  // call parent constructor
  A.call(this, aOptions);

  // do stuff with bOptions here...
}

现在,您可以调用 A(选项)新A(选项)以获得相同的结果.

Now you can call A(options) or new A(options) to get the same result.

与B相同, B(aOptions,bOptions)新B(aOptions,bOptions)将得到相同的结果.

Same with B, B(aOptions, bOptions) or new B(aOptions, bOptions) will get the same result.

这篇关于如何在javascript中扩展现有的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆