如何创建不可变对象

module.exports = function deepFreeze (o) {

    Object.freeze(o);

    Object.getOwnPropertyNames(o).forEach(function (prop) {

        if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === "object" || typeof o[prop] === "function")

                && !Object.isFrozen(o[prop])) {

            deepFreeze(o[prop]);

        }

    });

    return o;

}

推荐阅读更多精彩内容