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)
直接为对象构造方法添加的方法,不能被对象实例访问,只能供构造方法自身使用。
代码省略。。。。。。。。