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); }
也可以使用上面的修改方式对其成员变量的数据进行设置。