大家好我正在尝试javascript / node.js中的对象,实际上我很难对其中包含函数的对象进行操作。这是我的示例代码,输出应该是:
Rohan说:Hello World
这是我的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');
我希望你能帮助我在我的代码中解决这个问题。谢谢你们。
答案 0 :(得分:2)
见Correct javascript inheritance。 Don't use the new
keyword用于创建原型(您不希望像实例一样初始化它)。通过应用父构造函数初始化实例。对于命名约定:大写构造函数会很好。
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');
答案 1 :(得分:1)
将talk
功能修改为
this.talk = function (msg) {
console.log(this.name + ' says: ' + msg);
}
答案 2 :(得分: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');