sending data to client (data is an object with a b

2019-07-07 06:02发布

问题:

(would like to update a new client that logs in with a list of all chat rooms that were created so far)

Say I do something like this: (every time a person joins the app)

socket.emit('updateClient', rooms);

rooms is an object, consisting of many room instances of a Room object which is by itself small, but has a pretty big code as a prototype of room

Example of rooms:

var rooms = {};  // contain all "Room" instances
..
..
// 'room' will create new instance for every "room" created
var room= new Room();
// save reference in `rooms`
rooms[room.id] = room;
..
var Room = function(){
    this.id = RANDOM NUMBER
    this.people = []; // an array of people in the room
}

Room.prototype = {
    ...
    A LOT OF INNER FUNCTIONS
    THAT ARE IRRELEVANT TO THE CLIENT
    ...
}

My question is:

would the prototyped be sent along to the client? (wouldn't want that) and would it make the socket request "heavy" in the way I'm doing this?

回答1:

socket.io will probably use JSON.stringify to send any objects, and JSON.stringify only serializes an object's "own" properties (and will leave out any functions on top of that). So no, the serialized object that is sent won't be heavy. Just as well, it may not contain all the properties you expect. It will only contain those that you have explicitly set on the particular room object.

See How to stringify inherited objects to JSON? , Why is JSON.stringify not serializing prototype values? .