Private instance methods in JavaScript Part II
The previous article in this series, introduced the basics of OO class inheritance, using the prototype.js framework. In this post, I will demonstrate how it is possible to create private methods, that are accessible from within the class, but are inaccessible to calls from outside the class.
The key to solving this problem is to add the public instance methods as closures, including the ‘initialize ’ constructor. This allows a private member or method to be accessed from within the closure, using the premise that closures are able to access properties further up the hierarchy. At the same time, these same properties remain protected from outside the parent function.
Below, is an example of how to build a private class method, using prototype.js:
Bird = Class.create (Abstract, (function () { var string = "...and I have wings"; //private instance member var secret = function () { return string; } //private instance method return { initialize: function (name) { this.name = name; }, //constructor method say: function (message) { return this.name + " says: " + message + secret(); } //public method } })()); Owl = Class.create (Bird, { say: function ($super, message) { return $super(message) + "...tweet"; } //public method }) var bird = new Bird("Robin"); //instantiate console.log(bird.say("tweet")); //public method call var owl = new Owl("Barnie"); //instantiate console.log(owl.say("hoot")); //public method call inherit & add