Accessing private member variables from prototype-defined functions

前端 未结 25 1262
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  误落风尘
    2020-11-22 15:20

    I suggest it would probably be a good idea to describe "having a prototype assignment in a constructor" as a Javascript anti-pattern. Think about it. It is way too risky.

    What you're actually doing there on creation of the second object (i.e. b) is redefining that prototype function for all objects that use that prototype. This will effectively reset the value for object a in your example. It will work if you want a shared variable and if you happen to create all of the object instances up front, but it feels way too risky.

    I found a bug in some Javascript I was working on recently that was due to this exact anti-pattern. It was trying to set a drag and drop handler on the particular object being created but was instead doing it for all instances. Not good.

    Doug Crockford's solution is the best.

提交回复
热议问题