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

JavaScript 對象成員的可見性說明

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

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

  2,私有方法(private methods)
  與私有屬性類似,只能在對象構(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();//錯誤。使用trycatch的話,可捕獲“對象不支持此屬性或方法”異常
mt.invoke();

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

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

 ?。?)通過構(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)
  直接為對象構(gòu)造方法添加的屬性,不能被對象實例訪問,只能供構(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)
  直接為對象構(gòu)造方法添加的方法,不能被對象實例訪問,只能供構(gòu)造方法自身使用。
  代碼省略。。。。。。。。

相關(guān)文章

最新評論