我對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