0

我记得在某处读到函数参数变成了函数中的私有变量,所以我尝试了这个:

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();

它会提醒正确传入的参数,所以可以使用它来代替这样的东西:

var node = function(nParent,nName,nContent){
    var parent = nParent;
    var name = nName;
    var content = nContent;
    this.init = function(){
        alert(name+" "+parent+" "+content);
    }
};

我知道如果我想在将参数分配给私有变量之前对参数进行任何形式的额外验证检查,我将不得不使用第二个版本,如果参数已经是私有变量,我只是不想浪费空间永远不要去任何地方,这是合理的做法吗?谢谢,

4

2 回答 2

5

当然没关系。这些参数是实例化变量,与您设置的其他变量没有明显区别。

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

于 2012-05-10T22:01:11.243 回答
0

是的; 这很好。

于 2012-05-10T22:00:51.040 回答