学习笔记 —— Javascript的类(3)

本文介绍了一个JavaScript类中静态属性的定义及使用方法,并通过一个具体的示例演示了如何创建类、定义静态属性和方法,以及如何实例化对象并访问这些属性。
None.gif//定义一个类
None.gif
function TestClass(name)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
//初始化时总数+1
InBlock.gif
    TestClass.prototype.Count++;
InBlock.gif
InBlock.gif    
//定义一个属性,并设置默认值
InBlock.gif
    this.Name = name || "jxh";
InBlock.gif
InBlock.gif    
//定义一个静态类属性
InBlock.gif
    TestClass.prototype.Current.InternalName = this.Name;
InBlock.gif
InBlock.gif    
//定义一个对象属性
InBlock.gif
    this.internalClass = new InternalClass(this.Name);
InBlock.gif
InBlock.gif    
//定义一个方法
InBlock.gif
    this.GetFormatName = function()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        var fname 
= this.internalClass.FormatName();
InBlock.gif        
return fname;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
//为TestClass类定义一个静态属性
None.gif
TestClass.prototype.Count = 0;
None.gif
None.gif
//为TestClass类定义一个静态类属性
None.gif
TestClass.prototype.Current = new InternalClass("没有实例");
None.gif
None.gif
//内部类
None.gif
function InternalClass(name)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
this.InternalName = name;
ExpandedBlockEnd.gif}
对于静态属性的访问,除了 [类名.prototype.属性名] 的访问方式外,直接用 [对象名.属性名] 也能访问,但由于 [对象名.属性名] 的访问方式如果对属性做了修改的话, [对象名.属性名] 将不在和 [类名.prototype.属性名] 的值一致,可能会引起误会,所以建议对静态属性只使用[类名.prototype.属性名] 一种方式去访问。
None.gif<script language = "javascript">
None.gif    function Click_Event()
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        alert(
"没有实例对象");
InBlock.gif        alert(
"TestClass.prototype.Count:" + TestClass.prototype.Count);
InBlock.gif        alert(
"TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);
InBlock.gif
InBlock.gif        var testClass1 
= new TestClass(); 
InBlock.gif        alert(
"实例1个对象");
InBlock.gif        alert(
"TestClass.prototype.Count:" + TestClass.prototype.Count);
InBlock.gif        alert(
"TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);
InBlock.gif
InBlock.gif        var testClass2 
= new TestClass("jxhwei"); 
InBlock.gif        alert(
"实例2个对象");
InBlock.gif        alert(
"TestClass.prototype.Count:" + TestClass.prototype.Count);
InBlock.gif        alert(
"TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);
ExpandedBlockEnd.gif    }

None.gif
</script>

转载于:https://www.cnblogs.com/jxhwei/archive/2007/02/01/636523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值