Javascript node.js、require()和原型继承
我对node.js非常陌生,可能也不熟悉javascript,所以请随意指出任何看起来不太舒服的地方。我是来学习的 以下是我想做的:Javascript node.js、require()和原型继承,javascript,node.js,require,prototypal-inheritance,Javascript,Node.js,Require,Prototypal Inheritance,我对node.js非常陌生,可能也不熟悉javascript,所以请随意指出任何看起来不太舒服的地方。我是来学习的 以下是我想做的: “John”对象应该继承“Client”对象的所有内容,包括函数 在实例化新对象和继承时使用Object.create()而不是“new”关键字 下面是一个有效的单文件测试: var sys=require('sys'); var Client = { ip: null, stream : null, state: "Connecting",
- “John”对象应该继承“Client”对象的所有内容,包括函数
- 在实例化新对象和继承时使用Object.create()而不是“new”关键字
var sys=require('sys');
var Client = {
ip: null,
stream : null,
state: "Connecting",
eyes: 2,
legs: 4,
name: null,
toString: function () {
return this.name + " with " +
this.eyes + " eyes and " +
this.legs + " legs, " + this.state + ".";
}
}
var john = Object.create(Client, {
name: {value: "John", writable: true},
state : {value: "Sleeping", writable: true}
});
sys.puts(john); // John with 2 eyes and 4 legs, Sleeping
下面是我将其拆分为不同文件时发生的情况:
----client.js----
----约翰·杰斯----
----main.js----
问题:
inname
和instate
时输入的一个简单错误
关于#1:
我怀疑原来的单文件代码和新的3文件代码之间的另一个细微差别是错误的。一个特别的评论引起了我的注意,特别是
当然,如果构造函数中有实际的初始化代码,则Object.create不能反映它
您的client.js
文件正在生成一个构造函数。你想在john.js
中写的是(结合#1和#2):
调用客户机函数,使其返回一个对象而不是函数,然后在此基础上创建一个新对象
关于#3:
我不明白您为什么不能使用此模式,但您刚刚演示了它是:
new
),这样语法错误就不会像旧的Java风格语法那样“跳出来”记住这一点。我很高兴你问了这个问题,因为现在我知道了
对象。create
:) 这看起来像是一个语法错误。client.js中的exports函数缺少表示return{
和}的行代码>.Oops,你说得对。现在修好了。它在文件中只是没有正确地剪切和粘贴。我对输入错误感到非常尴尬。=^^=谢谢你抓住了!现在一切都好了,非常感谢!
module.exports = function (instream, inip){
return {
ip: inip,
stream : instream,
state: "Connecting",
eyes: 2,
legs: 4,
name: null,
toString: function () {
return this.name + " with " +
this.eyes + " eyes and " +
this.legs + " legs, " + this.state + ".";
},
};
};
var Client = require("./client");
module.exports = function (inname, instate){
return Object.create(Client, {
state : {value: inname, enumerable: false, writable: true},
name: {value: instate, enumerable: true, writable: true},
});
};
var sys = require("util");
var Client = require("./client")("stream","168.192.0.1");
sys.puts(Client); // null with 2 eyes and 4 legs, Connecting
var john = require("./john")("John","Sleeping");
sys.puts(john); //Function.prototype.toString no generic
sys.puts(sys.inspect(john)); // { name: 'Sleeping' }
sys.puts(sys.inspect(john, true)); // {name: 'Sleeping', [state]: 'John'}
return Object.create(Client, {
state : {value: inname, enumerable: false, writable: true},
name: {value: instate, enumerable: true, writable: true},
});
return Object.create(Client(), {
state : {value: instate, enumerable: false, writable: true},
name: {value: inname, enumerable: true, writable: true},
});