I have object whith method (function) on server (node.js). I want get this object with methods in browser.
Is it possible?
I made simple example on GitHub
There are server.js and index.html files. Run --> node server.
++++++++ UPD (after comments)
My object on server:
function ClassOrder(name, cost) {
this.name = name;
this.cost = cost;
this.parts = [];
this.summ = function() {
var summ = 0;
this.parts.forEach(function(part) {
summ += part.summ();
});
return summ + this.cost;
};
}
var myobject = new ClassOrder('my object', 10);
myobject.parts[0] = new ClassOrder('my first part', 20);
myobject.parts[1] = new ClassOrder('my second part', 30);
myobject.parts[1].parts[0] = new ClassOrder('my first in second part', 40);
console.log(myobject); // view myobject in console
console.log(myobject.summ()); // return 100 (10+20+30+40)
send to client (on request)
res.end(JSON.stringify(myobject));
and get it on client's javascript code (in browser)
function getobject() {
var xhr = new XMLHttpRequest();
xhr.open('get', '/getobject', true);
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
var myobject = JSON.parse(this.responseText);
console.log(myobject); // all data ok
console.log(myobject.summ()); // no methods!!
};
xhr.send(null);
}
It is a simple example and in real i use prototype (or inherit in util(node.js)). I use this methods on server and save it in DB. All work is ok. But if i wont use it on client i need copy-paste all methods, WHY?
Also i dont know how add my example method to my object in client without disassemble it.