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

前端 未结 4 1641
礼貌的吻别
礼貌的吻别 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:05

    Question by question:

    1. Basically, having the reset method in the prototype means that all instances of your constructor will share the exact same copy of the method. By creating a local method inside the constructor, you'll have one copy of the method per instance, which will consume more memory (this may become a problem if you have a lot of instances). Other than that, both versions are identical; changing function SomeObj to var SomeObj = function only differs on how SomeObj is hoisted on its parent scope. You said you "gained some privacy with the variable declarations", but I didn't see any private variables there...

    2. With the IIFE approach you mentioned, you'll lose the ability to check if instance instanceof SomeObj.

    3. Not sure if this answers your question, but there is also Object.create, where you can still set the prototype, but get rid of the new keyword. You lose the ability to have constructors, though.

提交回复
热议问题