[英]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 = myOtherVar; // ?????????????????
};
}
How can I set the private variable myOtherVar?如何设置私有变量 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/ 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();
In JavaScript it is a convention to prefix the name of private variables with an _ (underscore).在 JavaScript 中,使用 _(下划线)作为私有变量名称的前缀是一种约定。 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.在上面的代码中,我们将局部变量 myOtherVar 分配给私有变量 _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;我认为 this.myOthervar = myOtherVar; will corrupt the global namespace and created a variable window.myOtherVar in window object将破坏全局命名空间并在 window 对象中创建一个变量 window.myOtherVar
Maybe you can declare myOtherVar as MyOtherVar, taking advantage of javascript's case sensitiveness, then assign MyOtherVar=myOtherVar into the function:也许您可以将 myOtherVar 声明为 MyOtherVar,利用 javascript 区分大小写的优势,然后将 MyOtherVar=myOtherVar 分配给函数:
function Foo() {
var MyPrivateBool = false,
MyOtherVar;
this.bar = function(myOtherVar) {
MyPrivateBool = true;
MyOtherVar = myOtherVar;
};
}
试试this.myOtherVar = myOtherVar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.