我对node.js很陌生,也可能是javascript,所以随意指出一些看起来很尴尬的东西。我在这里学习。node.js,require()和原型继承
这里就是我想要做的事:
- “约翰”的对象应该继承一切从“客户”对象,包括代替“新”关键字功能
- 使用的Object.create()实例化新的对象和继承
这里是工作的单个文件测试:
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
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 + ".";
},
};
};
---- ---- john.js
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},
});
};
---- ---- main.js
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'}
问题:
- 我在分割文件和使用require()时会出现问题?
- 为什么约翰对象有“睡眠”的名称和“约翰”的状态?我知道这是我把行的顺序,但它应该不能说明我已经把在构造函数中的参数?
- 是否有这样做的更好的办法?我倾向于学习的Object.create(),而不是依赖于“新”的关键字。
这看起来像一个语法错误。 client.js中的exports函数缺少表示'return {'和'};'的行。 –
糟糕,你是对的。现在修复。它在文件中没有正确剪切和粘贴。 – howdoicodethis