【问题标题】:util inherits in nodeutil 在节点中继承
【发布时间】:2015-05-02 02:35:29
【问题描述】:

试图理解 node 的 util 包提供的继承支持。

var util = require('util');

//=========================================
function Foo(temp){
    this.y = temp;
}

Foo.prototype.yo = function(){
    console.log("Yo "+this.y);
}

//=========================================

function Bar(){}
util.inherits(Bar,Foo);

var b = new Bar(20);
//b.y = 10; 
b.yo();

这里 b.yo() 打印“Yo undefined”。它调用 Foo 的 yo() 所以我想继承是有效的。但它不打印 y 值。 如果 b.y = 10 行未注释,则打印 10 值。 试图了解为什么会发生这种情况。

【问题讨论】:

  • @hina10531 有什么关系?

标签: javascript node.js inheritance


【解决方案1】:

Bar的构造函数为空。

当你继承某些东西时,它会复制原型属性,但你必须自己正确地实现一个构造函数。

所以你在技术上可以做到这一点:

function Bar(temp) {
    Foo.call(this, temp);
}

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2016-08-14
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多