Heim  >  Artikel  >  Web-Frontend  >  JavaScript 对象成员的可见性说明_javascript技巧

JavaScript 对象成员的可见性说明_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:44:281251Durchsuche

JavaScript对象构造的可见性定义可以分为以下几种:
  1,私有属性(private properties)
  
  通过var关键字定义对象构造中变量的作用域,该变量只能在对象构造方法的作用域内被访问。如:

复制代码 代码如下:

function VariableTest()
{
var myVariable;//private
}
var vt = new VariableTest();
vt.myVariable;//这里会出现undefined异常

  2,私有方法(private methods)
  与私有属性类似,只能在对象构造方法作用域内被访问。如:
复制代码 代码如下:

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关键字来定义。如:
复制代码 代码如下:

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

  (2)通过构造方法的原型来定义。如:
复制代码 代码如下:

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

  4,公共方法(public methods)
  同理,有两种定义公共方法的途径。
  
  (1)通过this关键字来定义。(2)通过构造方法的原型来定义。
  这里省略。。。。。。。。。。。
  5,静态属性(static properties)
  直接为对象构造方法添加的属性,不能被对象实例访问,只能供构造方法自身使用。如:
复制代码 代码如下:

function StaticVariable(){}
StaticVariable.variable = "static variable";
var sv = new StaticVariable();
sv.variable;//返回"undefined"
StaticVariable.prototype.variable;//返回"undefined"
StaticVariable.variable;//返回"static variable"

  6,静态方法(static methods)
  直接为对象构造方法添加的方法,不能被对象实例访问,只能供构造方法自身使用。
  代码省略。。。。。。。。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn