Javascript node.js中的面向对象开发

Javascript node.js中的面向对象开发,javascript,node.js,Javascript,Node.js,使用nodejs创建了一个api服务器。作为前端开发的一种习惯,我在面向对象的结构中开发了它们,但我在写作时有一点感到困惑 var server = { component: { http: require("http"), fs: require("fs") }, start: function () { var instance=this; this.component.http.createServer(function (request, response

使用nodejs创建了一个api服务器。作为前端开发的一种习惯,我在面向对象的结构中开发了它们,但我在写作时有一点感到困惑

var server = {
component: {
    http: require("http"),
    fs: require("fs")
},
start: function () {
    var instance=this;
    this.component.http.createServer(function (request, response) {
        instance.component.fs.readFile(filename, "binary", function (err, file) {
            // do something with file
        });
    }).listen(80);
}
这是我在parameter函数中调用继承对象的方法。在这种情况下,是单个文件系统对象与所有连接共享,还是需要为每个新连接创建一个新的文件系统实例


edit:“instance”不是带标签的语句。

在您的示例中,每个连接都将重用文件系统对象

关于编码风格的建议:我非常确定您不需要使用带有“实例”标签的语句-事实上,我强烈建议您不要在js中使用它!带标签的语句通常与break或continue语句一起使用&事实上,在我的整个职业生涯中,我只见过几次使用它们。它们会把代码弄得一团糟&可能会把正在阅读您的代码的人弄糊涂。您可以阅读有关标签语句的更多信息

作为标签的替换,此处使用变量等。此外,如果您将开始将“this”赋值给例如变量(或示例中的标签),请尝试坚持该值并立即开始引用该变量-尽量不要将“this”与包含它的变量混合(如代码第8行)。然后,您的代码可以如下所示:

var server = {
component: {
    http: require("http"),
    fs: require("fs")
},
start: function () {
    var instance = this;
    instance.component.http.createServer(function (request, response) {
        instance.component.fs.readFile(filename, "binary", function (err, file) {
            // do something with file
        });
    }).listen(80);
}
对象作用域将在此处隔离“instance”,并允许它在“instance.component.http.createServer”回调中更深入


希望这个答案和建议能帮助您和其他JavaScript开发人员

关于这一点,什么是面向对象的?
实例
在代码中的任何地方都没有定义。可能是指
server.instance
,但也不是指
server
本身。我建议先阅读关于
this
和对象的MDN文档你真的想要
var instance=this