Home  >  Q&A  >  body text

javascript - js 继承问题

var util = require('util');
    function Base() {
        this.name = 'base';
        this.base = 1991;
        this.sayHello = function() {
            console.log('Hello ' + this.name);
        };
    }
    Base.prototype.showName = function() {
        console.log(this.name);
    };
    function Sub() {
        this.name = 'sub';
    }
    util.inherits(Sub, Base);

var objSub = new Sub();
console.log(objSub);

很明显会打印{ name: 'sub' }

Sub 仅仅继承了 Base 在原型中定义的函数,而构造函数内部创造的 base 属 性和 sayHello 函数都没有被 Sub 继承。

那么 如何继承构造函数内部创造的 base 属 性和 sayHello 函数 求解答

PHP中文网PHP中文网2749 days ago323

reply all(5)I'll reply

  • 怪我咯

    怪我咯2017-04-10 15:14:21

    function Sub() {
        Base.apply(this, arguments);
        this.name = 'sub';
    }
    

    js要自己调用父类的构造函数

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:14:21

    不知道你的 inherits 内部是怎么写的,推荐几篇文章吧
    http://yanhaijing.com/js/2014/11/09/object-inherit-of-js/
    http://yanhaijing.com/javascript/2014/05/15/a-code-explain-javascript-...

    reply
    0
  • 迷茫

    迷茫2017-04-10 15:14:21

    //新加代码
    __extends = function (child, parent) {
        child.prototype = new parent();
        child.prototype.constructor= child;
        return child;
    };
    //====================
        function Base() {
            this.name = 'base';
            this.base = 1991;
            this.sayHello = function() {
                console.log('Hello ' + this.name);
            };
        }
        Base.prototype.showName = function() {
            console.log(this.name);
        };
        function Sub() {
            this.name = 'sub';
        }
    
    __extends(Sub,Base);
    var obj = new Sub();
    obj.sayHello();
    

    reply
    0
  • 迷茫

    迷茫2017-04-10 15:14:21

    Sub.prototype = new Base();
    Sub.prototype.constructor = Sub;
    var sub1 = new Sub();
    console.log(sub1.base)

    reply
    0
  • 高洛峰

    高洛峰2017-04-10 15:14:21

    <<javascript高级程序设计 - 第5版>> 第六章 6.3继承;

    reply
    0
  • Cancelreply