Implementing Mozilla's toSource() method in Internet Explorer

后端 未结 8 879
轮回少年
轮回少年 2020-11-27 07:41

Has anyone implemented Mozilla\'s Object.toSource() method for Internet Explorer and other non-Gecko browsers? I\'m looking for a lightweight way to serialize simple object

8条回答
  •  渐次进展
    2020-11-27 07:56

    In order to take this a little further: when you send something - to work on - a receiver must get it and be able to work on it. So this next bit of code will do the trick - adapted from the previous answer by Eliran Malka.

    // SENDER IS WRAPPING OBJECT TO BE SENT AS STRING
    // object to serialize
    var s1 = function (str) {
        return {
            n: 8,
            o: null,
            b: true,
            s: 'text',
            a: ['a', 'b', 'c'],
            f: function () {
                alert(str)
            }
        }
    };
    // test
    s1("this function call works!").f();
    // serialized object; for newbies: object is now a string and can be sent ;)
    var code = s1.toString();
    
    // RECEIVER KNOWS A WRAPPED OBJECT IS COMING IN
    // you have to assign your wrapped object to somevar
    eval('var s2  = ' + code);
    // and then you can test somevar again
    s2("this also works!").f();
    

    Be aware of the use of eval. If you own all code being transferred: feel free to use it (although it can also have disadvantages). If you don't know where the source is coming from: it's a no-no.

    javascript object tosource stringify eval

提交回复
热议问题