0

大家好,我正在尝试使用 javascript/node.js 中的对象,实际上我很难处理其中包含函数的对象。这是我的示例代码,输出应该是:

罗汉 说:你好,世界

这是我的 func.js

var myObject = function(name) {
    console.log(this.name + ' says: ');
    this.talk = function(msg) {
        console.log(msg);
        }
};

var phil = function (name) {
    this.name = name;
};

phil.prototype = new myObject();
var man = new phil('Rohan');
man.talk('Hello World');

我希望你能帮助我在我的代码中解决这个问题。多谢你们。

4

3 回答 3

2

请参阅正确的 javascript 继承不要使用new关键字来创建原型(你不想像实例一样初始化它)。通过应用父构造函数来初始化实例。对于命名约定:大写构造函数会很好。

function MyObject() {
    console.log(this.name + ' got created');
}
MyObject.prototype.talk = function(msg) {
    console.log("and says "+msg);
};

function Phil(name) {
    this.name = name;
    MyObject.call(this);
}
Phil.prototype = Object.create(MyObject.prototype);

var man = new Phil('Rohan');
man.talk('Hello World');
于 2013-09-19T03:18:45.930 回答
1
var myObject = function(name) {
    this.talk = function(msg) {
        console.log(msg);
    },
    this.setName = function(name) {
        this.name = name;
        console.log(name + ' says: ');
    }
};

var phil = function (name) {
    this.setName(name);
};

phil.prototype = new myObject();
var man = new phil('Rohan');
man.talk('Hello World');
于 2013-09-19T03:29:50.717 回答
1

修改你的talk功能

this.talk = function (msg) {
    console.log(this.name + ' says: ' + msg);
}
于 2013-09-19T03:21:15.577 回答