Search code examples
javascriptecmascript-5

Putting methods on Object.getPrototypeOf(this)


See this class definition:

function MyClass (property) {
    // Private
    var privateVariable;
    var privateMethod = function () {};

    // Public
    this.publicProperty = property;
    this.publicPrivilegedMethodOnInstance = function () {};
    Object.getPrototypeOf(this).publicPrivilegedMethodOnPrototype = function () {};
}
MyClass.prototype.publicMethod = function () {};

var myMyClass = new MyClass('foo');

The method publicPrivilegedMethodOnPrototype is public, yet can access private variables (which publicMethod) can’t. It’s also shared on the prototype, which publicPrivilegedMethodOnInstance is not.

Any downsides of defining publicPrivilegedMethodOnPrototype like this? I guess ECMAScript 5 is a requirement, and that the method is redefined every time MyClass is instantiated.


Solution

  • It's a very bad idea.

    So you create many objects but as you're assigning the property to the prototype of all of them, at some point even functions which weren't meant to access certain values will do it... This is very odd.

    A given prototype function is meant to access properties from the object whose own the prototype using this:

    function X() {
       this.text = "hello world";
    }
    X.prototype.doStuff() {
       console.log(this.text);
    };
    

    Thus, avoid that anti-pattern. It makes no sense. My advise is that you need to deal with the absense of access modifiers in JavaScript instead of blindly looking for a workaround.