JavaScript类的静态成员及其修改对象实例的数据

王朝html/css/js·作者佚名  2008-08-25
窄屏简体版  字體: |||超大  

JavaScript静态成员的定义,只需要在类的构造函数之外,使用类的名称(即:构造函数的函数名称)来定义,如:

function MyClass(){}

MyClass.staticMethod = staticMethod;

function staticMethod(){}

JavaScript的静态成员变量的定义类似,如:

MyClass.STATIC_VAR = "SHIRDRN";

下面通过编写一个实例来说明,如下所示:

<script language="JavaScript" type="text/javascript">

function MyRect(w,h,id){

// 成员变量

this.id = id

this.rWidth = w;

this.rHeight = h;

// 成员方法

this.setId = setId;

this.setWidth = setWidth;

this.setHeight = setHeight;

this.newMyRect = newMyRect; // 获取一个MyRect对象实例的方法

this.getArea = getArea;

this.getPerimeter = getPerimeter;

}

MyRect.DEVELOP_OWNER = "SHIRDRN"; // 静态成员常量

MyRect.VERSION = "V 1.25";

MyRect.getVersion = getVersion; // 静态方法

function getVersion(){ // 静态方法的实现,获取版本号

return MyRect.VERSION;

}

function newMyRect(){ // 成员方法的实现,返回一个MyRect类的对象实例,可以通过修改默认值进行设置

return new MyRect("",0,0);

}

function setId(id){

this.id = id;

}

function setWidth(w){

this.rWidth = w;

}

function setHeight(h){

this.rHeight = h;

}

function getArea(){

var area = this.rWidth * this.rHeight;

return area;

}

function getPerimeter(){

var perimeter = 2*this.rWidth + 2*this.rHeight;

return perimeter;

}

</script>

访问静态成员变量的数据和调用静态成员方法,直接使用类名访问,如下所示:

alert(MyRect.getVersion()); // 调用静态方法

alert(MyRect.VERSION);

alert(MyRect.DEVELOP_OWNER);

静态成员变量(常量),不能对其值进行修改。但是,可以通过非静态的成员方法来修改对象实例的数据如下所示:

var myRectInstance = new MyRect("QQ10000",2008,800);

alert("Original value of id : " + myRectInstance.id);

alert("Original value of rWidth : " + myRectInstance.rWidth);

alert("Original value of rHeight : " + myRectInstance.rHeight);

myRectInstance.id = "QQ187071722"; // 直接通过访问成员变量进行修改

myRectInstance.rWidth = 1983;

myRectInstance.rHeight = 119;

alert("After modified,id : " + myRectInstance.id);

alert("After modified,rWidth : " +myRectInstance.rWidth);

alert("After modified,rHeight : " +myRectInstance.rHeight);

当然,可以使用我们定义的成员方法来修改,如下:

myRectInstance.setId("QQ187071722");

myRectInstance.setWidth(1983);

myRectInstance.setHeight(119);

与上面中间部分的代码功能是一样的。这样使用所谓的存取器(Setter和Getter)是不必要的,直接修改成员变量即可。

再看一下,我们定义了一个newRect()方法,它返回一个默认的对象实例:

function newMyRect(){ // 成员方法的实现,返回一个MyRect类的对象实例,可以通过修改默认值进行设置

return new MyRect("",0,0);

}

也可以使用上面的修改方式对其成员变量的数据进行设置。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航