function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function(myOtherVar) {
myPrivateBool = true;
myOtherVar = myOtherVar; // ?????????????????
};
}
如何設置私有變量myOtherVar?設置一個與函數參數同名的Javascript專用變量?
function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function(myOtherVar) {
myPrivateBool = true;
myOtherVar = myOtherVar; // ?????????????????
};
}
如何設置私有變量myOtherVar?設置一個與函數參數同名的Javascript專用變量?
給出的參數不同的名稱:
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();
嘗試this.myOtherVar = myOtherVar;
那設置一個屬性,而不是一個變量。 – user113716 2011-02-14 20:07:49
是不是讓它成爲公衆會員? – Garrett 2011-02-14 20:09:18
我認爲this.myOthervar = myOtherVar;將腐敗的全局命名空間開創了窗口對象的變量window.myOtherVar
也許你可以聲明myOtherVar爲MyOtherVar,以JavaScript的情況下,敏感的優勢,然後分配MyOtherVar = myOtherVar進入功能:
function Foo() {
var MyPrivateBool = false,
MyOtherVar;
this.bar = function(myOtherVar) {
MyPrivateBool = true;
MyOtherVar = myOtherVar;
};
}
我很害怕這將是它=(我想這是js – Garrett 2011-02-14 20:08:58
@Garrett的缺陷:是的,bar函數中的形式參數將比構造函數的變量更接近範圍鏈 – user113716 2011-02-14 20:12:23