简体   繁体   English

Javascript继承:我们如何继承使用new运算符从函数创建对象的对象和函数,并具有原型函数

[英]Javascript Inheritance: How can we inherit object and function where object is created from function using new operator and has prototype functions

I have fucntion A: 我有一个问题A:

function A() {} 
A.prototype.fnA() = function(){}

create a object: 创建一个对象:

a = new A()

I have function B: 我有功能B:

function B() {}
B.prototype.fnB = function(){}

I wish to inherit object a with instance of B so that new instace created will have proto functions of both A and B . 我希望继承具有B实例的对象a ,以便创建的新实例将具有AB原型函数。

How can I do that ? 我怎样才能做到这一点 ?

Following code does what you need: 以下代码可满足您的需求:

 'use strict'; function A() { // ... } A.prototype.fnA = function () { console.log('Running fnA()'); }; function B() { // ... } B.prototype = new A(); B.prototype.fnB = function () { console.log('Running fnB()'); }; var b = new B(); b.fnA(); b.fnB(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM