【问题标题】:Javascript Inheritance: How can we inherit object and function where object is created from function using new operator and has prototype functionsJavascript继承:我们如何继承对象和函数,其中对象是使用new运算符从函数创建并具有原型函数
【发布时间】:2017-03-12 11:27:06
【问题描述】:

我有功能A:

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

创建一个对象:

a = new A()

我有函数 B:

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

我希望用B 的实例继承对象a,以便创建的新实例将具有AB 的原型函数。

我该怎么做?

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

    以下代码可以满足您的需要:

    '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();

    【讨论】:

    • 这有帮助。但是我们如何使用 Object.create 函数实现相同的功能
    猜你喜欢
    • 2012-06-19
    • 2023-04-11
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多