function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function(myOtherVar) {
myPrivateBool = true;
myOtherVar = myOtherVar; // ?????????????????
};
}
如何设置私有变量myOtherVar?
为参数指定其他名称:
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"
或根据需要创建私有函数来设置值。
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();
在JavaScript中,惯例是在私有变量的名称前加上_(下划线)。遵循此约定,您可以将代码更改为。
function Foo() {
var _myPrivateBool = false,_myOtherVar;
this.bar = function(myOtherVar) {
_myPrivateBool = true;
_myOtherVar = myOtherVar;
};
}
在上面的代码中,我们将局部变量myOtherVar分配给私有变量_myOtherVar。这样看来,我们的私有变量和局部变量具有相同的名称。
注意:这只是一个约定。使用_开头的变量名不会使它成为私有变量。
我认为this.myOthervar = myOtherVar;将破坏全局名称空间并在窗口对象中创建一个变量window.myOtherVar
尝试this.myOtherVar = myOtherVar;
也许您可以利用JavaScript的大小写敏感性将myOtherVar声明为MyOtherVar,然后将MyOtherVar = myOtherVar分配给该函数:
function Foo() {
var MyPrivateBool = false,
MyOtherVar;
this.bar = function(myOtherVar) {
MyPrivateBool = true;
MyOtherVar = myOtherVar;
};
}