欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript 對(duì)象成員的可見(jiàn)性說(shuō)明

 更新時(shí)間:2009年10月16日 20:54:13   作者:  
與java等基于類(lèi)的面向?qū)ο笳Z(yǔ)言的private、protected、public等關(guān)鍵字的用途類(lèi)似,基于對(duì)象的JavaScript語(yǔ)言,在對(duì)象構(gòu)造上也存在類(lèi)似的成員可見(jiàn)性問(wèn)題。
JavaScript對(duì)象構(gòu)造的可見(jiàn)性定義可以分為以下幾種:
  1,私有屬性(private properties)
  
  通過(guò)var關(guān)鍵字定義對(duì)象構(gòu)造中變量的作用域,該變量只能在對(duì)象構(gòu)造方法的作用域內(nèi)被訪(fǎng)問(wèn)。如:
復(fù)制代碼 代碼如下:

function VariableTest()
{
var myVariable;//private
}
var vt = new VariableTest();
vt.myVariable;//這里會(huì)出現(xiàn)undefined異常

  2,私有方法(private methods)
  與私有屬性類(lèi)似,只能在對(duì)象構(gòu)造方法作用域內(nèi)被訪(fǎng)問(wèn)。如:
復(fù)制代碼 代碼如下:

function MethodTest()
{
var myMethod = function()//private
{
alert("private method");
}
this.invoke = function()
{
//能夠訪(fǎng)問(wèn)到myMethod
myMehtod();
}
}
var mt = new MethodTest();
mt.myMethod();//錯(cuò)誤。使用trycatch的話(huà),可捕獲“對(duì)象不支持此屬性或方法”異常
mt.invoke();

  3,公共屬性(public properties)
  有兩種定義公共屬性的途徑:
  (1)通過(guò)this關(guān)鍵字來(lái)定義。如:
復(fù)制代碼 代碼如下:

function PrivilegedVariable()
{
this.variable = "privileged variable";
}
var pv = new PrivilegedVariable();
pv.variable;//返回 "privileged variable"

 ?。?)通過(guò)構(gòu)造方法的原型來(lái)定義。如:
復(fù)制代碼 代碼如下:

function PublicVariable(){}
PublicVariable.prototype.variable = "public variable";
var pv = new PublicVariable();
pv.variable;//返回"public variable"

  4,公共方法(public methods)
  同理,有兩種定義公共方法的途徑。
  
 ?。?)通過(guò)this關(guān)鍵字來(lái)定義。(2)通過(guò)構(gòu)造方法的原型來(lái)定義。
  這里省略。。。。。。。。。。。
  5,靜態(tài)屬性(static properties)
  直接為對(duì)象構(gòu)造方法添加的屬性,不能被對(duì)象實(shí)例訪(fǎng)問(wèn),只能供構(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í)例訪(fǎng)問(wèn),只能供構(gòu)造方法自身使用。
  代碼省略。。。。。。。。

相關(guān)文章

最新評(píng)論