JavaScript Jems - The Revealing Constructor Pattern |
Written by Mike James | ||||
Thursday, 27 March 2025 | ||||
Page 3 of 3
The Revealing ConstructorThe solution to the mistake is simple enough – pass the required private members as parameters to the function. This is what you do whenever you need a function to work with values that exist but are not in scope - that's what parameters are for. For example: var myObject = new myClass( function (reveal) { console.log(reveal()); } ); Note that the function needs to be called within the constructor with a parameter: function myClass(func) { var myPrivateVar = Math.random(); var reveal = function () { return myPrivateVar;}; func(reveal); } Now it all works but it looks very strange. When you look at the constructor call you get the uneasy feeling that it is wrong because reveal hasn't been defined - it isn't in scope. However, reveal in this case is a parameter in the function definition and nothing to do with any reveal that is within the constructor. The function passed to the constructor can call private functions within the constructor as long as they are passed to it when the function is called. Notice that you can just as well write: var myObject = new myClass( function (firstParameter) { console.log(firstParameter());} ); The name used for the first parameter is irrelevant just like that of any parameter – it only has meaning within the function that it is a parameter of. The value of the first parameter, i.e. the function to be passed in, only becomes fixed when the constructor calls the function. That is, when it reaches: func(reveal); Notice that, after the constructor has finished its job, no other function can call reveal except for methods of the object constructed. It is private to the object and only accessible by closure. The general principles of the revealing constructor pattern are:
The revealing constructor pattern is generally useful to allow external code restricted access to private functions within a constructor. It is, of course, how the Promise constructor allows you access to the resolve and reject functions - but only within the constructor – and this makes it a jem. Now available as a book from your local Amazon.JavaScript Jems:
|
||||
Last Updated ( Saturday, 29 March 2025 ) |