0

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,

1
  • Did you mean to say alert(name+" "+parent+" "+content); Commented May 10, 2012 at 22:04

2 Answers 2

5

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 arguments instead, then there would be a difference: in code readability, in even performance (there's a penalty for using arguments).

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

Yes; that's perfectly fine.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.