P
P
pofigizm2014-06-15 02:41:08
JavaScript
pofigizm, 2014-06-15 02:41:08

How to transfer from the server (node.js) an object along with methods (function)?

On the server (node.js) I created an object that has fields and a method (function).

I send this object as JSON to the browser. In the browser, I get an object consisting only of data. My method is no longer there. Actually the question is how to get an object with a method (s)?

I don’t know where to post an example with a node, so I just put it on github.

There are two files server.js and index.html .
Download to any folder and type node server on the command line .
Then open the address in the browser: 127.0.0.1 .
After clicking on the link in the console my Object and TypeError .

https://github.com/Pofigizm/nodejs-send-object-exa...

+++ UPD

Made through the Function constructor (thanks Denis Pushkarev ) . Almost what I wanted, but you need to write methods in the form of texts, which is not very convenient to work with.
https://github.com/Pofigizm/nodejs-send-object-exa...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Pushkarev, 2014-06-15
@pofigizm

JSON is a format for exchanging data, not code, and only supports primitives, Object and Array, but not functions. Would you like to submit a code? Connect it as a script or pass it as text data and execute it via the Function or eval constructor.

Y
Yuri Gubich, 2014-06-15
@Arhangel64

I do not quite understand why you need to receive methods from the server? Perhaps you need something different? You may be interested in template engines like ejs.
Such a system works here. You connect the templating system, describe the template, and the server does not issue the command res.render('template name', {3D object}). Further in the template, you can already freely access the methods and properties of the passed object.
But, of course, this method will "render" the page only once, after it is returned to the user for browser javascript, of course, the object, in its classical representation, will not be available.
If you still need to get an object with methods from the server, it’s more convenient to come up with something json. True, you will have to collect all the methods in functions from strings, as the previous commentator wrote. Object.method = new Function([arguments], "method body").

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question