1

I create a object in a Node server and a send it throught Jade:

module.exports = class Object {
    constructor() {
        this.foo = "bar";
    }

    getFoo() {
        return this.foo;
    }
}

Server.js file:

var ob = new Object();

app.get('/', function (req, res) {
    res.render('index', {object : ob});
});

When I try to use the object on the client

var ob = !{JSON.stringify(object)};
console.log(ob.getFoo());

I get the error that the variable "ob" has no function "getFoo", the client requests object.js where is described the Object class. I don't think this is the right way, but it's the only one I know.

First question, non native English speaker, hope everything is at least fine.

Mattia
  • 11
  • 1
  • 2
    `class Object`. That's as bad as it can get. Choose another name for your class, don't use existing names that belong to native types. – ibrahim mahrir Apr 23 '18 at 23:15
  • 1
    @Luca it thows an error here. – Mark Apr 23 '18 at 23:21
  • 1
    @Luca No. It's Jade as mentioned... In plain JS it would've been invalid syntax since a block is not an expression – Andrew Li Apr 23 '18 at 23:22
  • It's also not clear what you mean by, 'When I try to use the object on the client'. Are you talking about using the object and function in you jade template, or in a script run in the browser. The later is not going to work — you can't stringify the function. – Mark Apr 23 '18 at 23:23
  • 1
    To OP: Because you're stringifying the object, it's now a JSON string. A string doesn't have the method anymore. You'll have to find a way to return the object back into its instance form (assuming you rename it from `Object`)... – Andrew Li Apr 23 '18 at 23:23
  • 1
    `JSON.stringify` strips all functions (and some other stuff too) from your object. `JSON.stringify({a: 5, b: function() {}})` => `{"a":5}` – ibrahim mahrir Apr 23 '18 at 23:25
  • Yes, the name is Object just to be clear, I'll try to pass the object in others way, thanks to everyone! You all really rock! – Mattia Apr 24 '18 at 06:18

0 Answers0