2012-06-05 88 views
3

我对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'} 

问题:

  1. 我在分割文件和使用require()时会出现问题?
  2. 为什么约翰对象有“睡眠”的名称和“约翰”的状态?我知道这是我把行的顺序,但它应该不能说明我已经把在构造函数中的参数?
  3. 是否有这样做的更好的办法?我倾向于学习的Object.create(),而不是依赖于“新”的关键字。
+0

这看起来像一个语法错误。 client.js中的exports函数缺少表示'return {'和'};'的行。 –

+0

糟糕,你是对的。现在修复。它在文件中没有正确剪切和粘贴。 – howdoicodethis

回答

2

在#2:

return Object.create(Client, { 
    state : {value: inname, enumerable: false, writable: true}, 
    name: {value: instate, enumerable: true, writable: true}, 
}); 

这是在你的身边交换innameinstate一个简单的错误输入。

在#1:

我怀疑原单文件代码和新的3档代码之间的另一个微小的差别是有过错的。一则留言引起了我的眼睛MDN's page on Object.create,具体而言,

当然,如果在构造函数中实际的初始化代码,该的Object.create不能反映它

client.js文件产生构造函数。你的意思在john.js写的是(合并#1和#2):

return Object.create(Client(), { 
    state : {value: instate, enumerable: false, writable: true}, 
    name: {value: inname, enumerable: true, writable: true}, 
}); 

呼叫客户端功能,因此它返回一个对象,而不是一个函数,然后创建建立在之上的新对象那。

在#3:

我不明白为什么你不能使用这种模式,但你刚才证实,它是:

  1. 国外对大多数JavaScript对象是如何创建的今天(尽管毫无疑问是一种更快的施工机制)。
  2. 使用更新的语法(即删除new),因此语法错误不会像使用旧的Java风格的语法那样“跳出来”。

只要记住这一点。我很高兴你问这个问题,因为现在我知道Object.create。 :)

+0

我完全尴尬的迷雾。 = ^^ =感谢您的支持!现在一切正常,非常感谢! – howdoicodethis