Setting a Javascript Private Variable with the same name as a Function Parameter?
function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function(myOtherVar) {
myPrivateBool = true;
myOtherVar = myOth开发者_如何学GoerVar; // ?????????????????
};
}
How can I set the private variable myOtherVar?
Give the parameter a different name:
function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function( param ) {
myPrivateBool = true;
myOtherVar = param;
};
this.baz = function() {
alert( myOtherVar );
};
}
var inst = new Foo;
inst.bar( "new value" );
inst.baz(); // alerts the value of the variable "myOtherVar"
http://jsfiddle.net/efqVW/
Or create a private function to set the value if you prefer.
function Foo() {
var myPrivateBool = false,
myOtherVar;
function setMyOtherVar( v ) {
myOtherVar = v;
}
this.bar = function(myOtherVar) {
myPrivateBool = true;
setMyOtherVar( myOtherVar );
};
this.baz = function() {
alert(myOtherVar);
};
}
var inst = new Foo;
inst.bar("new value");
inst.baz();
http://jsfiddle.net/efqVW/1/
In JavaScript it is a convention to prefix the name of private variables with an _ (underscore). Following this convention you can change your code to.
function Foo() {
var _myPrivateBool = false,_myOtherVar;
this.bar = function(myOtherVar) {
_myPrivateBool = true;
_myOtherVar = myOtherVar;
};
}
In the above code we are assigning the local variable myOtherVar to the private variable _myOtherVar. This way it looks like we have the same name for the private and local variables.
Note:This is just a convention followed.Prefixing a variable name with _ does not make it a private variable.
I think this.myOthervar = myOtherVar; will corrupt the global namespace and created a variable window.myOtherVar in window object
Try this.myOtherVar = myOtherVar;
Maybe you can declare myOtherVar as MyOtherVar, taking advantage of javascript's case sensitiveness, then assign MyOtherVar=myOtherVar into the function:
function Foo() {
var MyPrivateBool = false,
MyOtherVar;
this.bar = function(myOtherVar) {
MyPrivateBool = true;
MyOtherVar = myOtherVar;
};
}
精彩评论