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 函数 求解答
怪我咯2017-04-10 15:14:21
function Sub() {
Base.apply(this, arguments);
this.name = 'sub';
}
js要自己调用父类的构造函数
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-...
迷茫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();
迷茫2017-04-10 15:14:21
Sub.prototype = new Base();
Sub.prototype.constructor = Sub;
var sub1 = new Sub();
console.log(sub1.base)