JSON serializing an object with function parameter

后端 未结 3 1585
失恋的感觉
失恋的感觉 2021-01-01 22:46

I have this C# object:

var obj = new {
    username = \"andrey\",
    callback = \"function(self) { return function() {self.doSomething()} (this) }\"
}
         


        
3条回答
  •  天命终不由人
    2021-01-01 23:07

    You can make use of the constructor of the Function object. See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Function.

    In your json you set the callback property to a string array that describes the Function constructor parameters. Then when the json data has arrived on the client you have to convert the Array to an instance of the Function object.

    This way you can have the function implementation details in your back database instead of hardcoded in source code.

    const json = '{"username":"andrey","callback":["self","return self.doSomething()"]}';
    
    //Parse the json to an object
    const object = JSON.parse(json);
    
    //Convert the callback property from Array to Function
    object["callback"] = new Function(...object["callback"]);
    
    //Create a parameter for calling the Function
    var self = {
        doSomething() {
            console.log("Do something called");
        }
    }
    
    //Call the function
    object["callback"](self);
    

提交回复
热议问题