我想定義在類定義(這是一個jQuery插件中的普通函數構造函數)的所有實例中使用的單個變量。如何在JavaScript中定義一個可用於實例的公共變量?
有這樣的功能嗎?
如果有,只是一個簡單的演示,我想我會明白。
我想定義在類定義(這是一個jQuery插件中的普通函數構造函數)的所有實例中使用的單個變量。如何在JavaScript中定義一個可用於實例的公共變量?
有這樣的功能嗎?
如果有,只是一個簡單的演示,我想我會明白。
你的問題不是很清楚。你的意思是一個全局變量嗎?可以從任何對象訪問的變量?
EDIT(基於評論)
你可以做這樣的事情,使變量範圍的只是你的代碼:
//This function will execute right away (it is basically the same as leaving it out,
//except that anything inside of it is scoped to it.
(function(){
var globalToThisScope = "this is global ONLY from within this code section";
window.object = {
//Now any instance of this object can see that variable,
// but anything outside of the outer empty function will not see anything
};
})();
只能從類**的任何實例**中訪問的全局變量。 – user198729 2010-01-14 17:09:23
然後只聲明一個全局變量。 window.varname =「this is global」; – 2010-01-14 17:10:14
請參閱我的修改答案,以獲得完成之後的工作。 – 2010-01-15 21:35:04
的Javascript doen't確實提供這種數據隱藏,但是這可能會滿足你的目的:
function A()
{
if (!A.b) A.b = 1;//shared
//this.b = 0;//not shared
}
A.prototype.getB = function()
{
return A.b;//shared
//return this.b;//not shared
}
A.prototype.setB = function(value)
{
A.b = value;//shared
//this.b = value//not shared
}
function load()
{
var x = new A();
var y = new A();
y.setB(2);
document.body.innerHTML += x.getB();
}
輸出:2
你正在尋找的是一個private static
或protected static
變量,它不能100%在JavaScript中模擬(我知道)。
但是,您可以製作public static
或private
。
tehMick的解決方案給你public static
一些方便setter/getters,但它真的沒有什麼不同,如果你用A.b = 2
代替y.setB(2)
。
這裏有一個私有變量將如何工作,但明白,這仍然是一個每個實例變量,反映了通過僅僅是因爲每個實例將其設置爲相同的文字串,吸氣相同的值。
function SomeClass()
{
var privateVariable = 'foo';
this.publicVariable = 'bar';
this.getPrivateVariable = function()
{
return privateVariable;
}
this.setPrivateVariable = function(value)
{
privateVariable = value;
}
}
SomeClass.staticVariable = 'baz';
var a = new SomeClass();
var b = new SomeClass();
// Works...
alert(a.getPrivateVariable());
alert(b.getPrivateVariable());
// Until we try to set it...
a.setPrivateVariable('hello');
// Then it breaks
alert(a.getPrivateVariable());
alert(b.getPrivateVariable());
我同意Peter Bailey(+1)。公共和私有實例變量的Douglas Crockford has a discussion;彼得提出了添加靜態公共變量的好方法。
JavaScript沒有任何被正式稱爲類的東西,所以你真的需要發佈代碼來展示你如何定義和實例化「類」。 – noah 2010-01-14 17:51:31