People say that everything in The prototypal inheritance is public But we can achieve privacy using closures in the constructor right?

function Cons(id){

So why in every single book i come through they say prototypal inheritance is global and has no privacy involved?

1 Answer 1


Please take care to make a distinction between abstract language features like prototypical inheritance, and their implementation in specific languages such as JavaScript.

Prototypical inheritance does not in itself forbid concepts such as public/private access. Protected access cannot meaningfully exist because every object delegates unhandled messages to its prototype, i.e. is an ordinary client of the prototype (aside from setting this).

In a pure OOP system, private visibility is not meaningful as objects are defined solely through their public interface. Anything else is an implementation detail of that object. However, this view is not very useful in practice.

Most dynamic languages (incl. Smalltalk, Perl, Python, JavaScript, …) have no strict enforcement of method/field visibility. Instead, most rely on conventions. The practical reason for this is that you would have to decide whether a private call was made from within an object. In a static language like Java that's easy to decide at compile time, but not in JavaScript where you can dynamically patch methods into an object. In fact, JavaScript has no concept of compile- vs run-phase. Some approaches e.g. in Python try to inspect the callstack and raise a runtime exception when a “private” method is called, but those solutions are fragile and imply a runtime overhead.

You are completely right that you can use closures to have private access to data. But this is orthogonal to prototypical inheritance. While unusual, I could use similar approaches in a some class-based language like Python, though now I'd get a new class for each object (because the methods must close over different private data).

The result is that you can express objects with truly private state in JavaScript, but this is not because of fundamental features or restrictions of prototypical inheritance, but because of the combination of the “prototypical inheritance” language feature with the mostly unrelated “closures” language feature.

  • In order to understand OO in ECMAScript, you have to understand that from the point of view of OO, what ECMAScript calls an "object" is actually a dictionary, and what ECMAScript calls a "function" is actually an object. IOW, how you build objects in ECMAScript is by using closures. Commented Jun 21, 2018 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.