首页 > js 继承问题

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 函数 求解答


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

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


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


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


//新加代码
__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();

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

【热门文章】
【热门文章】