Moving from `prototype` and `new` to a closure-and-exposure pattern

前端 未结 4 1643
礼貌的吻别
礼貌的吻别 2021-01-21 14:07

I have been re-factoring someone else\'s JavaScript code.

BEFORE:

function SomeObj(flag) {
    var _private = true;
    this.flag = (fla         


        
4条回答
  •  后悔当初
    2021-01-21 15:02

    In my experience, the only thing you lose by not using .prototype is memory - each object ends up owning its own copy of the function objects defined therein.

    If you only intend instantiating "small" numbers of objects this is not likely to be a big problem.

    Regarding your specific questions:

    1. The second comment on that linked article is highly relevant. The author's benchmark is wrong - it's testing the overhead of running a constructor that also declares four inner functions. It's not testing the subsequent performance of those functions.

    2. Your "closure and expose" code sample is not OO, it's just a namespace with some enclosed private variables. Since it doesn't use new it's no use if you ever hope to instantiate objects from it.

    3. I can't answer this - "it depends" is as good an answer as you can get for this.

提交回复
热议问题