LJSON

Posted by Bruce Tsai
06/07/2016

LJSON 是個 JSON 的擴充格式,改變只有一個,就是多了可以儲存 pure function 的能力,儲存 function 的形式是很像 ES6 arrow function 的樣子:

var LJSON = require("./LJSON.js");

// A random JS object with a pure function inside.
var person = {
    name : "John",
    mail : function(msg){ return { author  : "John", message : msg}; }
};

// If JSON was used, the `mail` field would be stripped from `personVal`.
var personStr = LJSON.stringify(person); 
var personVal = LJSON.parse(personStr);
var mail      = personVal.mail("hello"); // would crash with JSON

// But, since `mail` is pure, LJSON can deal with it correctly:
console.log("Serialized value : " + personStr);
console.log("Calling mail     : " + LJSON.stringify(mail));

Output

Serialized value : {"name":"John","mail":(v0)=>({"author":"John","message":v0})}
Calling mail     : {"author":"John","message":"hello"}

最大的差別在於=>後面是接(),並且還有個特色是它會想辦法最佳化,會有像是 dead code removal 的效果。如果要自己做到用 JSON 儲存 function 的話,一般是可以先用toString來輸出 function 的原始碼,要還原時再用 new Function 來還原,不過如果不是 pure function,例如有用到 closure 變數的話,就一定會失去這些 reference 到的變數了。

results matching ""

    No results matching ""