I remember reading somewhere that function arguments get turned into private variables within the function so I tried this:
var node = function(nParent,nName,nContent){
this.init = function(){
alert(nName+" "+nParent+" "+nContent);
}
};
var a = new node("A - parent","A - name","A - content");
var b = new node("B - parent","B - name","B - content");
a.init();
b.init();
which alerts the correct passed in arguments so is this ok to use instead of something like this:
var node = function(nParent,nName,nContent){
var parent = nParent;
var name = nName;
var content = nContent;
this.init = function(){
alert(name+" "+parent+" "+content);
}
};
I know I would have to use the second version if I wanted to do any form of extra validation checking on the arguments before assigning them to the private variables, I just didn’t want to waste space if the arguments are already private variables that will never go anywhere, is this a reasonable thing to do?
Thanks,
Of course it’s okay. These arguments are instantiated variables, with no appreciable difference from the other variables you set them to.
Now, if you didn’t use any named parameters, and used
argumentsinstead, then there would be a difference: in code readability, in even performance (there’s a penalty for usingarguments).Only downside to all of this is that your variable definitions won’t all be in the same place. (Assuming that there would be any more variable definitions and assignments in this function, beyond the params passed.)