如何访问node.js中对象的成员

时间:2021-03-15 15:23:35

I'm really new to node.js and having a bit of a problem with objects. Lets say I have two files, one called printer.js and another called database.js. printer.js prints the results database returns. printer.js looks like this:

我是node.js的新手,并且对象有点问题。假设我有两个文件,一个名为printer.js,另一个名为database.js。 printer.js打印结果数据库返回。 printer.js看起来像这样:

var db = require("./database")

db.getStations(dbReturn);

function dbReturn(stations) {
    for(var i = 0; i < stations.length; i++) {
        console.log('id: ' + stations.id);
    }
}

and my database.js looks like this:

我的database.js看起来像这样:

function getStations(callback){
    var listOfStations = [];

    for(var index = 0; index < 10; index++) {
        var station = new Station(index);
        listOfStations[index] = station;
    }
    callback(listOfStations);
}

function Station(id){
    this.id = id;
}

exports.getStations = getStations;

I would just like to mention that Station class has a lot more members than that. But the problem here is that I cannot access the members from the Station objects I created in database.js from printer.js. I am having quite a bit of trouble figuring out how to do this. I have learned how to create a new object of Station in printer.js by exporting Station, but I still can't access the members of an object I created somewhere else! It just spits out 10 x "id: undefined"

我想提一下,Station类的成员比这个要多得多。但问题是我无法从printer.js中的database.js中创建的Station对象访问成员。我在弄清楚如何做到这一点时遇到了很多麻烦。我已经学会了如何通过导出Station在printer.js中创建一个新的Station对象,但我仍然无法访问我在其他地方创建的对象的成员!它吐出10 x“id:undefined”

I have been suggested to do something similar to this:

我被建议做类似的事情:

database.prototype.getStations = function(callback) {
    //...
}

database.prototype.Station = function(id) {
    //...
}

module.exports = database;

But this does not seem to work since it just tells me that database is undefined. What am I doing wrong here?

但这似乎不起作用,因为它只是告诉我数据库是未定义的。我在这做错了什么?

1 个解决方案

#1


2  

You're not accessing the stations by index in your for loop.

您没有在for循环中通过索引访问工作站。

Change this in printer.js:

在printer.js中更改此内容:

console.log('id: ' + stations.id);

to:

至:

console.log('id: ' + stations[i].id);

#1


2  

You're not accessing the stations by index in your for loop.

您没有在for循环中通过索引访问工作站。

Change this in printer.js:

在printer.js中更改此内容:

console.log('id: ' + stations.id);

to:

至:

console.log('id: ' + stations[i].id);