|
1,私有屬性(private properties)
通過var關(guān)鍵字定義對(duì)象構(gòu)造中變量的作用域,該變量只能在對(duì)象構(gòu)造方法的作用域內(nèi)被訪問。如:
復(fù)制代碼 代碼如下:
function VariableTest()
{
var myVariable;//private
}
var vt = new VariableTest();
vt.myVariable;//這里會(huì)出現(xiàn)undefined異常
2,私有方法(private methods)
與私有屬性類似,只能在對(duì)象構(gòu)造方法作用域內(nèi)被訪問。如:
復(fù)制代碼 代碼如下:
function MethodTest()
{
var myMethod = function()//private
{
alert("private method");
}
this.invoke = function()
{
//能夠訪問到myMethod
myMehtod();
}
}
var mt = new MethodTest();
mt.myMethod();//錯(cuò)誤。使用trycatch的話,可捕獲“對(duì)象不支持此屬性或方法”異常
mt.invoke();
3,公共屬性(public properties)
有兩種定義公共屬性的途徑:
(1)通過this關(guān)鍵字來定義。如:
復(fù)制代碼 代碼如下:
function PrivilegedVariable()
{
this.variable = "privileged variable";
}
var pv = new PrivilegedVariable();
pv.variable;//返回 "privileged variable"
(2)通過構(gòu)造方法的原型來定義。如:
復(fù)制代碼 代碼如下:
function PublicVariable(){}
PublicVariable.prototype.variable = "public variable";
var pv = new PublicVariable();
pv.variable;//返回"public variable"
4,公共方法(public methods)
同理,有兩種定義公共方法的途徑。
(1)通過this關(guān)鍵字來定義。(2)通過構(gòu)造方法的原型來定義。
這里省略。。。。。。。。。。。
5,靜態(tài)屬性(static properties)
直接為對(duì)象構(gòu)造方法添加的屬性,不能被對(duì)象實(shí)例訪問,只能供構(gòu)造方法自身使用。如:
復(fù)制代碼 代碼如下:
function StaticVariable(){}
StaticVariable.variable = "static variable";
var sv = new StaticVariable();
sv.variable;//返回"undefined"
StaticVariable.prototype.variable;//返回"undefined"
StaticVariable.variable;//返回"static variable"
6,靜態(tài)方法(static methods)
直接為對(duì)象構(gòu)造方法添加的方法,不能被對(duì)象實(shí)例訪問,只能供構(gòu)造方法自身使用。
代碼省略。。。。。。。。
JavaScript技術(shù):JavaScript 對(duì)象成員的可見性說明,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。