How to define private constructors in javascript?

前端 未结 4 1226
旧巷少年郎
旧巷少年郎 2020-12-25 15:09

I have defined pure objects in JS which expose certain static methods which should be used to construct them instead of the constructor. How can I make a constructor for my

4条回答
  •  难免孤独
    2020-12-25 15:19

    Simply don't expose the constructor function. The core issue with the original code is the "static method" is defined as a property of the constructor (which is used as a "class") as opposed a property of the module.

    Consider:

    return {
        mkNewScore: Score.mkNewScore
        // .. and other static/module functions
    };
    

    The constructor can still be accessed via .constructor, but .. meh. At this point, might as well just let a "clever user" have access.

    return {
        mkNewScore: function (score) {
            var s = new Score(score, score >= 33);
            /* Shadow [prototype]. Without sealing the object this can
               be trivially thwarted with `del s.constructor` .. meh.
               See Bergi's comment for an alternative. */
            s.constructor = undefined;
            return s;
        }
    };
    

提交回复
热议问题