Variable privacy in Javascript's behaviour delegation pattern - javascript

Since my last question, I've been studying Javascript's prototype model and trying to get rid of the OOP vision I inherited from other languages (pun slightly intended).
I went back to basics and read Crookford's Javascript: The Good Parts, along with You Don't Know JS material and decided to stick with the so called behaviour delegation.
Restructuring my previous example implementing behaviour delegation and namespacing, I wrote:
var GAME = {};
(function(namespace) {
var Warrior = {};
Warrior.init = function(weapon) {
this.setWeapon(weapon);
};
Warrior.getWeapon = function() {
return this.weapon;
};
Warrior.setWeapon = function(value) {
this.weapon = value || "Bare hands";
};
namespace.Warrior = namespace.Warrior || Warrior;
})(GAME);
(function(namespace) {
var Archer = Object.create(namespace.Warrior);
Archer.init = function(accuracy) {
this.setWeapon("Bow");
this.setAccuracy(accuracy);
};
Archer.getAccuracy = function() {
return this.accuracy;
};
Archer.setAccuracy = function(value) {
this.accuracy = value;
};
namespace.Archer = namespace.Archer || Archer;
})(GAME);
So, everytime I copy a new Archer object:
var archer1 = Object.create(GAME.Archer);
only this object will be created, conserving memory.
But what if I don't want to expose "accuracy" attribute? The attribute would only increase by calling a "training()" method or something similar. I tried to use var accuracy inside the anonymous function, but it turns into kind of static variable, all instances of Archer would share the same value.
The question: Is there any way to set a variable as private while still keeping behaviour-delegation/prototypal pattern?
I do know of functional pattern as well, Here I succesfully achieved variable privacy, at the cost of memory. By going functional, every new "archer" instance generates a new "Warrior" and then a new "Archer". Even considering that Chrome and Firefox have different optmizations, testings on both report that the Delegation/Prototypal pattern is more efficient:
http://jsperf.com/delegation-vs-functional-pattern
If I go with the pure-object delegation pattern, should I just forget the classic encapsulation concept and accept the free changing nature of properties?

I would try to answer your question with something that is slightly different then this one that tells you how to use a library.
Different in that it will(hopefully) give you some ideas of how can we tackle the problem of private vars in OLOO ourselves. At least to some extent, with our own code, no external lib needed, which could be useful in certain scenarios.
In order for code to be cleaner I've striped your anonymous wrapper functions, since they are not related to problem in any way.
var Warrior = {};
Warrior.warInit = function (weapon){
this.setWeapon(weapon);
}
Warrior.getWeapon = function(){
return this.weapon;
}
Warrior.setWeapon = function (value){
this.weapon = value || "Bare hands";
}
var Archer = Object.create(Warrior);
Archer.archInit = function (accuracy){
this.setWeapon("Bow");
this.setAccuracy(accuracy);
}
Archer.getAccuracy = function (pocket) {
return pocket.accuracy;
}
Archer.setAccuracy = function (value, pocket){
pocket.accuracy = value;
}
function attachPocket(){
var pocket = {};
var archer = Object.create(Archer);
archer.getAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]);
return Archer.getAccuracy.apply(this, args)
};
archer.setAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]);
return Archer.setAccuracy.apply(this, args);
};
return archer;
}
var archer1 = attachPocket();
archer1.archInit("accuracy high");
console.log(archer1.getAccuracy()); // accuracy high
archer1.setAccuracy("accuracy medium");
console.log(archer1.getAccuracy()); // accuracy medium
Test code above here. (and open your browser console)
Usage
1 ) General practice in OLOO about naming functions on different levels of prototype chain is apposite from OOP. We want different names that are more descriptive and self documenting, which brigs code that is cleaner and more readable. More importantly, by giving different names we avoid recursion loop:
Archer.init = function(accuracy, pocket){
this.init() // here we reference Archer.init() again, indefinite recurson. Not what we want
...
}
Archer.archInit = fucntion (accuracy, pocket){ // better,
this.warInit() // no name "collisions" .
}
2 ) We've created an attachPocket() function that creates internal variable pocket. Creates new object with Object.create() and sets it's prototype to point to Archer. Pause. If you notice, functions that required a private var we have defined so that each of them take one more parameter(pocket), some use just pocket. Here is the trick.
By making wrapper functions like archer.setAccuracy(), archer.getAccuracy()
... we can create closures and call directly functions that need
private var (here pocket) and pass it to them as an argument.
Like so:
function AtachPocket(){
...
var pocket = {};
archer.setAccuracy = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]); // appending pocket to args
return Archer.setAccuracy(this, args);
};
...
}
Essencially by doing this we are bypassing what would have been a normal search for functions in prototype chain, just for functions that have need for a private var. This is what "call directly" refers to.
By setting the same name for a function in archer("instance") like it is in prototype chain (Archer) we are shadowing that function at the instance level. No danger of having indefinite loops, since we are "calling directly" like stated above. Also by having the same function name we preserve the normal, expected behaviour of having access to same function in an "instance" like it is in a prototype chain. Meaning that afther var archer = Object.create(Archer) we have access to function setAccuracy like we would if it had been normal search for function in prototype chain.
3 ) Every time attachPocket() is invoked it creates a new "instance" that has those wrapper functions that pass a pocket argument (all as an internal detail of implementation). And therefore every instance has own, unique, private variable.
You would use functions in an "instance" normally:
archer1.archInit("accuracy high"); // Passing needed arguments.
// Placed into pocked internally.
archer1.getAccuracy(); // Getting accuracy from pocket.
Scalability
Up to now all we have is function that "attaches a pocket" with hardcoded values like Archer.setAccuracy, Archer.getAccuracy. What if we would like to expand prototype chain by introducing a new object type like this var AdvancedArcher = Object.create(Archer), how the attachPocket is going to behave if we pass to it AdvancedArcher object that might not even have setAccuracy() function? Are we going to change attachPocket() each time we introduce some change in prototype chain ?
Let's try to answer those questions, by making attachPocket() more general.
First, expand prototype chain.
var AdvancedArcher = Object.create(Archer);
AdvancedArcher.advInit = function(range, accuracy){
this.archInit(accuracy);
this.setShotRange(range);
}
AdvancedArcher.setShotRange = function(val){
this.shotRange = val;
}
More generic attachPocket.
function attachPocketGen(warriorType){
var funcsForPocket = Array.prototype.slice.call(arguments,1); // Take functions that need pocket
var len = funcsForPocket.length;
var pocket = {};
var archer = Object.create(warriorType); // Linking prototype chain
for (var i = 0; i < len; i++){ // You could use ES6 "let" here instead of IIFE below, for same effect
(function(){
var func = funcsForPocket[i];
archer[func] = function(){
var args = Array.prototype.slice.call(arguments);
args = args.concat([pocket]); // appending pocket to args
return warriorType[func].apply(this, args);
}
})()
}
return archer;
}
var archer1 = attachPocketGen(Archer,"getAccuracy","setAccuracy");
archer1.advInit("11","accuracy high");
console.log(archer1.getAccuracy()); // "accuracy high";
archer1.setAccuracy("accuracy medium");
console.log(archer1.getAccuracy());
Test the code here.
In this more generic attachPocketGen as first argument we have a warriorType variable that represents any object in our prototype chain. Arguments that may fallow are ones that represent names of functions that need a private var.
attachPocketGen takes those function names and makes wrapper functions with same names in archer "instance". Shadowing, just like before.
Another thing to recognise is that this model of making wrapper functions and using apply() function to pass variables from closures is going to work for functions that use just pocket, functions that use pocket and other variables, and when ,of course, those variables use the relative this reference in front of them.
So we have achieved somewhat more usable attachPocket, but that are still things that should be noticed.
1) By having to pass names of functions that need private var, that usage implies that we(attachPocketGen users) need to know whole prototype chain (so we could see what functions need private var). Therefore if you are to make a prototype chain like the one here and just pass the attachPocketGen as an API to the programmer that wants to use your behaviour-delegation-with-private-variables, he/she would had to analyse objects in prototype chain. Sometimes that is not what wee want.
1a) But we could instead, when defining our functions in prototype chain (like Archer.getAccuracy) to add one property to them like a flag that can tell if that function have need for a private var:
Archer.getAccuracy.flg = true;
And then we could add additional logic that checks all functions in prototype chain that have this flg and fills the funcsForPocket.
Result would be to have just this call:
var archer1 = attachPocketGen(AdvancedArcher)
No other arguments except warriorType. No need for user of this function to have to know how prototype chain looks like, that is what functions have need for a private var.
Improved style
If we are to look at this code:
Archer.archInit = function (accuracy){
this.setWeapon("Bow");
this.setAccuracy(accuracy);
}
We see that it uses "pocket" function setAccuracy. But we are not adding pocket here as last argument to it because setAccuracy that gets called is shadowed version, the one from instance. Becouse it will be called only from an instance like so archer1.archInit(...) That one is already adding a pocket as last argument so there is on need to. That's kinda nice, but the definition of it is:
Archer.setAccuracy = function (value, pocket){ ...
and that can be confusing when making objects in prototype chain like Archer.archInit above. If we look the definition of setAccuracy it looks like we should it. So in order not have to remember that we don't have to add pocket as last arg in functions (like archInit) that use other pocket functions, maybe we should to something like this:
Archer.setAccuracy = function (value){
var pocket = arguments[arguments.length -1];
pocket.accuracy = value;
}
Test the code here.
No pocket as last argument in function definition. Now it's clear that function doesn't have to be called with pocket as an argument wherever in code.
1 ) There are other arguably minor stuff to refer to when we think about more general prototype chain and attachPocketGen.Like making functions that use pocket callable when we dont wan't to pass them a pocket, that is to toggle pocket usage to a function, but in order not to make this post too long, let's pause it.
Hope this can give you view ideas for solution to your question.

Related

private function return the last instance [duplicate]

Stylistically, I prefer this structure:
var Filter = function( category, value ){
this.category = category;
this.value = value;
// product is a JSON object
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
};
To this structure:
var Filter = function( category, value ){
this.category = category;
this.value = value;
};// var Filter = function(){...}
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
Functionally, are there any drawbacks to structuring my code this way? Will adding a prototypical method to a prototype object inside the constructor function's body (i.e. before the constructor function's expression statement closes) cause unexpected scoping issues?
I've used the first structure before with success, but I want to make sure I'm not setting myself for a debugging headache, or causing a fellow developer grief and aggravation due to bad coding practices.
Functionally, are there any drawbacks to structuring my code this way?
Will adding a prototypical method to a prototype object inside the
constructor function's body (i.e. before the constructor function's
expression statement closes) cause unexpected scoping issues?
Yes, there are drawbacks and unexpected scoping issues.
Assigning the prototype over and over to a locally defined function, both repeats that assignment and creates a new function object each time. The earlier assignments will be garbage collected since they are no longer referenced, but it's unnecessary work in both runtime execution of the constructor and in terms of garbage collection compared to the second code block.
There are unexpected scoping issues in some circumstances. See the Counter example at the end of my answer for an explicit example. If you refer to a local variable of the constructor from the prototype method, then your first example creates a potentially nasty bug in your code.
There are some other (more minor) differences. Your first scheme prohibits the use of the prototype outside the constructor as in:
Filter.prototype.checkProduct.apply(someFilterLikeObject, ...)
And, of course, if someone used:
Object.create(Filter.prototype)
without running the Filter constructor, that would also create a different result which is probably not as likely since it's reasonable to expect that something that uses the Filter prototype should run the Filter constructor in order to achieve expected results.
From a run-time performance point of view (performance of calling methods on the object), you would be better off with this:
var Filter = function( category, value ){
this.category = category;
this.value = value;
// product is a JSON object
this.checkProduct = function( product ){
// run some checks
return is_match;
}
};
There are some Javascript "experts" who claim that the memory savings of using the prototype is no longer needed (I watched a video lecture about that a few days ago) so it's time to start using the better performance of methods directly on the object rather than the prototype. I don't know if I'm ready to advocate that myself yet, but it was an interesting point to think about.
The biggest disadvantage of your first method I can think of is that it's really, really easy to make a nasty programming mistake. If you happen to think you can take advantage of the fact that the prototype method can now see local variables of the constructor, you will quickly shoot yourself in the foot as soon as you have more than one instance of your object. Imagine this circumstance:
var Counter = function(initialValue){
var value = initialValue;
// product is a JSON object
Counter.prototype.get = function() {
return value++;
}
};
var c1 = new Counter(0);
var c2 = new Counter(10);
console.log(c1.get()); // outputs 10, should output 0
Demonstration of the problem: http://jsfiddle.net/jfriend00/c7natr3d/
This is because, while it looks like the get method forms a closure and has access to the instance variables that are local variables of the constructor, it doesn't work that way in practice. Because all instances share the same prototype object, each new instance of the Counter object creates a new instance of the get function (which has access to the constructor local variables of the just created instance) and assigns it to the prototype, so now all instances have a get method that accesses the local variables of the constructor of the last instance created. It's a programming disaster as this is likely never what was intended and could easily be a head scratcher to figure out what went wrong and why.
While the other answers have focused on the things that are wrong with assigning to the prototype from inside the constructor, I'll focus on your first statement:
Stylistically, I prefer this structure
Probably you like the clean encapsulation that this notation offers - everything that belongs to the class is properly "scoped" to it by the {} block. (of course, the fallacy is that it is scoped to each run of the constructor function).
I suggest you take at the (revealing) module patterns that JavaScript offers. You get a much more explicit structure, standalone constructor declaration, class-scoped private variables, and everything properly encapsulated in a block:
var Filter = (function() {
function Filter(category, value) { // the constructor
this.category = category;
this.value = value;
}
// product is a JSON object
Filter.prototype.checkProduct = function(product) {
// run some checks
return is_match;
};
return Filter;
}());
The first example code kind of misses the purpose of the prototype. You will be recreating checkProduct method for each instance. While it will be defined only on the prototype, and will not consume memory for each instance, it will still take time.
If you wish to encapsulate the class you can check for the method's existence before stating the checkProduct method:
if(!Filter.prototype.checkProduct) {
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
}
There is one more thing you should consider. That anonymous function's closure now has access to all variables inside the constructor, so it might be tempting to access them, but that will lead you down a rabbit hole, as that function will only be privy to a single instance's closure. In your example it will be the last instance, and in my example it will be the first.
Biggest disadvantage of your code is closing possibility to override your methods.
If I write:
Filter.prototype.checkProduct = function( product ){
// run some checks
return different_result;
}
var a = new Filter(p1,p2);
a.checkProduct(product);
The result will be different than expected as original function will be called, not my.
In first example Filter prototype is not filled with functions until Filter is invoked at least once. What if somebody tries to inherit Filter prototypically? Using either nodejs'
function ExtendedFilter() {};
util.inherit(ExtendedFilter, Filter);
or Object.create:
function ExtendedFilter() {};
ExtendedFilter.prototype = Object.create(Filter.prototype);
always ends up with empty prototype in prototype chain if forgot or didn't know to invoke Filter first.
Just FYI, you cannot do this safely either:
function Constr(){
const privateVar = 'this var is private';
this.__proto__.getPrivateVar = function(){
return privateVar;
};
}
the reason is because Constr.prototype === this.__proto__, so you will have the same misbehavior.

Cannot combine dynamic prototype pattern with prototype chaining [duplicate]

Stylistically, I prefer this structure:
var Filter = function( category, value ){
this.category = category;
this.value = value;
// product is a JSON object
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
};
To this structure:
var Filter = function( category, value ){
this.category = category;
this.value = value;
};// var Filter = function(){...}
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
Functionally, are there any drawbacks to structuring my code this way? Will adding a prototypical method to a prototype object inside the constructor function's body (i.e. before the constructor function's expression statement closes) cause unexpected scoping issues?
I've used the first structure before with success, but I want to make sure I'm not setting myself for a debugging headache, or causing a fellow developer grief and aggravation due to bad coding practices.
Functionally, are there any drawbacks to structuring my code this way?
Will adding a prototypical method to a prototype object inside the
constructor function's body (i.e. before the constructor function's
expression statement closes) cause unexpected scoping issues?
Yes, there are drawbacks and unexpected scoping issues.
Assigning the prototype over and over to a locally defined function, both repeats that assignment and creates a new function object each time. The earlier assignments will be garbage collected since they are no longer referenced, but it's unnecessary work in both runtime execution of the constructor and in terms of garbage collection compared to the second code block.
There are unexpected scoping issues in some circumstances. See the Counter example at the end of my answer for an explicit example. If you refer to a local variable of the constructor from the prototype method, then your first example creates a potentially nasty bug in your code.
There are some other (more minor) differences. Your first scheme prohibits the use of the prototype outside the constructor as in:
Filter.prototype.checkProduct.apply(someFilterLikeObject, ...)
And, of course, if someone used:
Object.create(Filter.prototype)
without running the Filter constructor, that would also create a different result which is probably not as likely since it's reasonable to expect that something that uses the Filter prototype should run the Filter constructor in order to achieve expected results.
From a run-time performance point of view (performance of calling methods on the object), you would be better off with this:
var Filter = function( category, value ){
this.category = category;
this.value = value;
// product is a JSON object
this.checkProduct = function( product ){
// run some checks
return is_match;
}
};
There are some Javascript "experts" who claim that the memory savings of using the prototype is no longer needed (I watched a video lecture about that a few days ago) so it's time to start using the better performance of methods directly on the object rather than the prototype. I don't know if I'm ready to advocate that myself yet, but it was an interesting point to think about.
The biggest disadvantage of your first method I can think of is that it's really, really easy to make a nasty programming mistake. If you happen to think you can take advantage of the fact that the prototype method can now see local variables of the constructor, you will quickly shoot yourself in the foot as soon as you have more than one instance of your object. Imagine this circumstance:
var Counter = function(initialValue){
var value = initialValue;
// product is a JSON object
Counter.prototype.get = function() {
return value++;
}
};
var c1 = new Counter(0);
var c2 = new Counter(10);
console.log(c1.get()); // outputs 10, should output 0
Demonstration of the problem: http://jsfiddle.net/jfriend00/c7natr3d/
This is because, while it looks like the get method forms a closure and has access to the instance variables that are local variables of the constructor, it doesn't work that way in practice. Because all instances share the same prototype object, each new instance of the Counter object creates a new instance of the get function (which has access to the constructor local variables of the just created instance) and assigns it to the prototype, so now all instances have a get method that accesses the local variables of the constructor of the last instance created. It's a programming disaster as this is likely never what was intended and could easily be a head scratcher to figure out what went wrong and why.
While the other answers have focused on the things that are wrong with assigning to the prototype from inside the constructor, I'll focus on your first statement:
Stylistically, I prefer this structure
Probably you like the clean encapsulation that this notation offers - everything that belongs to the class is properly "scoped" to it by the {} block. (of course, the fallacy is that it is scoped to each run of the constructor function).
I suggest you take at the (revealing) module patterns that JavaScript offers. You get a much more explicit structure, standalone constructor declaration, class-scoped private variables, and everything properly encapsulated in a block:
var Filter = (function() {
function Filter(category, value) { // the constructor
this.category = category;
this.value = value;
}
// product is a JSON object
Filter.prototype.checkProduct = function(product) {
// run some checks
return is_match;
};
return Filter;
}());
The first example code kind of misses the purpose of the prototype. You will be recreating checkProduct method for each instance. While it will be defined only on the prototype, and will not consume memory for each instance, it will still take time.
If you wish to encapsulate the class you can check for the method's existence before stating the checkProduct method:
if(!Filter.prototype.checkProduct) {
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}
}
There is one more thing you should consider. That anonymous function's closure now has access to all variables inside the constructor, so it might be tempting to access them, but that will lead you down a rabbit hole, as that function will only be privy to a single instance's closure. In your example it will be the last instance, and in my example it will be the first.
Biggest disadvantage of your code is closing possibility to override your methods.
If I write:
Filter.prototype.checkProduct = function( product ){
// run some checks
return different_result;
}
var a = new Filter(p1,p2);
a.checkProduct(product);
The result will be different than expected as original function will be called, not my.
In first example Filter prototype is not filled with functions until Filter is invoked at least once. What if somebody tries to inherit Filter prototypically? Using either nodejs'
function ExtendedFilter() {};
util.inherit(ExtendedFilter, Filter);
or Object.create:
function ExtendedFilter() {};
ExtendedFilter.prototype = Object.create(Filter.prototype);
always ends up with empty prototype in prototype chain if forgot or didn't know to invoke Filter first.
Just FYI, you cannot do this safely either:
function Constr(){
const privateVar = 'this var is private';
this.__proto__.getPrivateVar = function(){
return privateVar;
};
}
the reason is because Constr.prototype === this.__proto__, so you will have the same misbehavior.

Define JavaScript get and set function in object without using "this"?

I have a simple global object with a get and set function. JSlint is not liking that I am using "this" in the get and set function because it violates "use strict". What would I replace "this" with so that it would not violate "use strict" (i.e. how go I reference the same thing "this" is referencing without using "this")?
function fnDirty() {
"use strict";
var bIsdirty = false;
this.get_bIsdirty = function() {return bIsdirty; };
this.set_bIsdirty = function(x) {bIsdirty = x; };
}
var GV_oDirty = new fnDirty();
By convention, constructor functions begin with capital letters. JSLint will allow use of this in strict mode if you are in a constructor function but yours begins with a lowercase letter so it does not get recognized as a constructor.
function FnDirty() {
//your code
}
To answer your remaining question: "What is the roundabout way of doing this without a constructor?"
Brian had the right-ish idea -- but what he was really creating was a singular object with private properties, rather than a factory.
So to that end, if you wanted a function which granted each instance of the "class" its own unique copy of the private property, you could do this (I'm going to illustrate an actual class of something more useful than "Foo" and "Bar", to better-illustrate the concept -- it should be very simple to recompose this into whatever your intended use is):
var makeWallet = function (starting_amount) {
var amount = starting_amount,
overdraft = 1000,
addAmount = function (added_funds) { amount += added_funds; },
deductAmount = function (extracted_amound) {
if (is_sufficient_funds(amount, overdraft, extracted_amount)) {
amount -= extracted_amount;
return makeWallet(extracted_amount);
}
},
// other needed public/helper methods here...
// checkBalance(), is_sufficient_funds(), etc...
public_interface = {
// add all public-API methods you need here
addFunds : addAmount,
deductFunds : deductAmount
};
return public_interface;
};
Now, you've got a function which will return an object. Each object has methods which access that object's own "private" (ie: closed-over) amount variable, which is unique to those methods and only accessible to those methods.
Whether you build the functions as vars in the private scope, or build them as function declarations in the private scope, or put them directly into a return { func1 : () {...},... }; is irrelevant, as long as they're defined inside of that function when it's called (ie: not on the prototype chain -- which you CAN'T use in this pattern, anyway -- you will NOT call this function with new).
Okay, so that's all well and good. You've now got a working wallet-maker (without the security and user-features, yadda-yadda... ...homework).
But what if you wanted to add PRIVATE STATIC members to that?
What if you needed to keep track of serial keys, so that you could issue bank cards to people? Or you needed to track the branch-number? This is where Brian's IIFE comes into play. Except that instead of returning the finished wallet object, it's going to return the wallet FACTORY.
var makeWallet = (function () {
var serial_num = 0,
branch_num = "A011002z";
function walletMaker = function (starting_amount) {
/*same function as before, except that you ALSO call:
serial_num += 1; in the construction of the wallet, and assign the id */
var id = serial_num += 1;
return wallet;
}
// then you return the wallet-factory
// which becomes the new value of the outer function
return walletMaker;
}());
Now you've got static properties (in the outermost closure, that the wallet-factory will have permanent access to, as "static" members), AND you have instance-based private members, which inner-methods, added during the creation of the instance-object, will have complete access to.
The only downsides to this are:
Lose the prototype ability for this particular class, because you aren't using a constructor. Meh. If your objects need this setup, then it's worth not having it...
...if they don't, and public-everything is cool, then just use a constructor, and prototype -- or just build inline objects, with no methods, and build services (functions) to operate on each similarly-built object.
If you build all objects this way, you're going to suffer a memory penalty, when you make thousands of these, or tens of thousands of these objects, each with their own copies of functions (to enclose the private references). Again, this is the price you pay for the functionality. Take the memory hit where security/clean interfaces are a must, and don't, where you don't need to.
Also goes without saying, but avoid using this in financial-institutions, as client-facing code isn't the best place to trust with the power to add and remove real money...
Hope that clears things up.
You can use an alternative approach:
var fnDirty = (function() {
var _isDirty = false;
return {
get_dirty: function() { return _isDirty; },
set_dirty: function(val) { _isDirty = value; }
};
})();

Recursively call "parent" constructors in Javascript?

I am working on a webapp that has something like a class hierarchy created through prototype-based inheritance. We're constantly adding features to a common ancestor "class" so its constructor signature is constantly expanding.
Each time we change the ancestor's signature, we'll also have to propagate the changes to thedescendants' constructors. This is obviously a maintainability problem, so I created a function that extracts the arguments for the parent from the arguments object and calls the parent using Function.apply().
The code looks like this:
BaseClass.prototype._super = function(args) {
args = Array.prototype.slice.call(args, this.constructor.length);
this.parentConstructor.apply(this, args);
};
and used like this:
function Child(child_arg1, child_arg2 /*, implicit parent args */) {
this._super(arguments);
}
(I can't use arguments.caller.arguments because the code is strict mode.
this.parentConstructor is set by the function building the class hierarchy.)
Unfortunately, this only works for one level of inheritance: for example, if A's parent class B has its own parent class C, when B calls _super, this.parentConstructor still points at B which means B will end up calling itself in an infinite loop.
If I store the parentConstructor field with the constructor Functions objects (instead of in the prototypes), I'll have to pass in the current calling function. This will make the line calling super tightly coupled to the surrounding function, which I am trying to avoid.
Thus does anyone know any better ways?
I asked a related question a couple days ago and Kamyar Nazeri's answer helped me a lot.
The way to avoid your problem is to define _super in a closure where the new constructor is defined so that it always references the correct parent object. The following pattern has worked very well for me:
var BaseClass =
{
create: function() // Basically a constructor
{
var obj = Object.create({});
obj.someProperty = "initial value based on arguments";
return obj;
};
};
var Child = (function buildChild(){
var obj = BaseClass.create("some value", "another argument")
, _super = Object.getPrototypeOf(obj);
// override BaseClass.create()
obj.create = function()
{
var obj = _super.create.apply(this, arguments);
// Child specific initializations go here
return obj;
};
return obj;
})(); // note that this gets called right away
var c = Child.create("some argument", "another thing");
console.log(BaseClass.isPrototypeOf(c)); // true
Note that for older browsers you will need to provide shims for Object.create() and Object.getPrototypeOf(). I've found this ECMAScript 5 shim to be helpful. I typically only pull out the shims that I'm using.

Would this be a good way to do private functions?

Just saw some interesting code while doing a typo in coffee-script. I got the following code
var Mamal, mam;
Mamal = (function() {
var __priv_func;
function Mamal() {}
Mamal.prototype.simple_var = 5;
Mamal.prototype.test = function() {
return __priv_func(this);
};
__priv_func = function(instance) {
return alert(instance.simple_var);
};
return Mamal;
})();
mam = new Mamal();
mam.simple_var = 10;
mam.test();
Now I've read alot about the module pattern in javascript and why its a bad thing (takes more memory, longer to create...) but of course the upside is having truly private functions/variables. Wouldn't the above code be a good way to create private functions (this wouldn't work for variables, unless you wanted static private variables) as the function is only created once in the closure?
One of the upsides of the module pattern is also the execution speed of functions as the code doesn't have to look up the prototype chain. Would this theoretically give the same speed improvements?
To highlight the points I was making, because clearly there was more to the question than just the title:
Yes a module pattern is a good and commonly used way to create private (er, local) data (functions or whatever), and export some sort of interface. Since a function is the only way to create variable scope, it's the only way to create private functions.
Because the functions will be shared by all objects created from Mamal, they're not useful for a functional inheritance pattern (references to functional inheritance have been removed from the question).
There's no performance improvement over lookups in the prototype chain, because the prototype chain needs to be traversed anyway just to get to your private functions.
To address specific questions points in the updated post:
"Would this be a good way to do private functions?"
Sure, but that's because having a function nested in another is the only way to scope a function.
"Now I've read alot about the module pattern in javascript and why its a bad thing..."
For a one-time use module, I don't see any issue. Also, any data referenced by variables that are no longer needed after the module function exits is free for garbage collection. This wouldn't be the case if they were global, unless you nullified them.
"...of course the upside is having truly private functions/variables..."
Yes, though some would take exception to the use of the word "private". Probably "local" is a better word.
"...this wouldn't work for variables, unless you wanted static private variables..."
Yes, though again some may take exception to the use of the word "static".
"Wouldn't the above code be a good way to create private functions...as the function is only created once in the closure?"
Yes again, nested functions are the only way to make them "private" or rather local.
But yes, as long as the function only ever needs to access the public properties of the objects (which are accessible to any code that can access the object) and not local variables of the constructor, then you should only create those functions once, whether or not you use a module pattern.
"One of the upsides of the module pattern is also the execution speed of functions as the code doesn't have to look up the prototype chain. Would this theoretically give the same speed improvements?"
No, you haven't exported your private functions directly, but rather the only way to call them is by traversing the prototype chain.
But if you ditched the prototype chain, and added functions as properties directly on the objects created, then you'd have some improvement there.
Here's an example:
Mamal = (function() {
var __priv_func;
function Mamal() {
this.test = __priv_func;
}
Mamal.prototype.simple_var = 5;
__priv_func = function() {
return alert( this.simple_var );
};
return Mamal;
})();
Now you've eliminated the prototype chain in the lookup of the test function, and also the wrapped function call, and you're still reusing the __priv_func.
The only thing left that is prototyped is the simple_var, and you could bring that directly onto the object too, but that'll happen anyway when you try to modify its value, so you might as well leave it there.
Original answer:
If you're talking about a module pattern, where you set up a bunch of code in (typically) an IIFE, then export methods that have access to the variables in the anonymous function, then yes, it's a good approach, and is pretty common.
var MyNamespace = (function () {
// do a bunch of stuff to set up functionality
// without pollution global namespace
var _exports = {};
_exports.aFunction = function() { ... };
_exports.anotherFunction = function() { ... };
return _exports;
})();
MyNamespace.aFunction();
But in your example, I don't see and advantage over a typical constructor, unless you decide to use the module pattern as above.
The way it stands right now, the identical functionality can be accomplished like this without any more global pollution, and without the wrapped function:
var Mamal, mam;
Mamal = function() {};
Mamal.prototype.test = function() {
return console.log(this.simple_var);
};
Mamal.prototype.simple_var = 5;
mam = new Mamal();
mam.simple_var = 10;
mam.test();
" Wouldn't the above code be a good way to create private functions (this wouldn't work for variables, unless you wanted static private variables) as the function is only created once in the closure?"
Given the rewritten code above, the function is still only created once. The prototype object is shared between objects created from the constructor, so it too is only created once.
"One of the upsides of functional inheritance is also the execution speed of functions as the code doesn't have to look up the prototype chain. Would this theoretically give the same speed improvements?"
In your code, the function is called via a function in the prototype chain, so it has that same overhead, plus the overhead of finding the local function in the variable scope and invoking that function as well.
So two lookups and two function invocation instead of one lookup and one invocation.
var Mamal, mam1, mam2;
Mamal = (function() {
//private static method
var __priv_func = function() {
return 1;
};
function Mamal() {
}
Mamal.prototype.get = function() {
return __priv_func();
};
Mamal.prototype.set = function(i) {
__priv_func = function(){
return i;
};
};
return Mamal;
})();
mam1 = new Mamal();
mam2 = new Mamal();
console.log(mam1.get()); //output 1
mam2.set(2);
console.log(mam1.get()); //output 2
The function __priv_func is not only private, but also static. I think it's a good way to get private function if 'static' does not matter.
Below is a way to get private but not static method. It may take more memory, longer to create.......
var Mamal, mam1, mam2;
function Mamal() {
//private attributes
var __priv_func = function() {
return 1;
};
//privileged methods
this.get = function() {
return __priv_func();
};
this.set = function(i) {
__priv_func = function(){
return i;
};
};
}
mam1 = new Mamal();
mam2 = new Mamal();
console.log(mam1.get()); // output 1
console.log(mam2.get()); // output 1
mam2.set(2);
console.log(mam1.get()); // output 1
console.log(mam2.get()); // output 2

Categories

Resources