Welcome 微信登录

首页 / 脚本样式 / JavaScript / javascript面向对象编程:如何定义属性字段

javascript面向对象编程:如何定义属性字段2014-09-19 csdn博客 xuexiaodong2009都知道js变量有作用域的概念,因此可以使用这个特性定义私有字段,私有字段的初始化主要是通过构造函数。

例如如下定义了一个只读字段first

function ListCommon2(afirst) { var first=afirst; this.GetFirst=function ()//定义了一个访问读取字段的特权方法{ return first;}}ListCommon2.prototype.do2=function() {var field= this.GetFirst();//在实例方法中利用特权方法读取字段 alert(field); }function test(){//测试代码 var t2=new ListCommon2("烧水2"); t2.do2();// }

当然如果需要一个修改字段的方法,也可以定义一个和读取字段类似的特权方法。

如下:

function ListCommon2(afirst) { var first=afirst; this.GetFirst=function ()//定义了一个访问读取字段的特权方法{ return first;} this.SetFirst=function (newvalue)//定义了一个设置字段的特权方法{ return first=newvalue;}}ListCommon2.prototype.do2=function() {var field= this.GetFirst();//在实例方法中利用特权方法读取字段 alert(field); }function test(){//测试代码 var t2=new ListCommon2("烧水2"); t2.SetFirst("测试");//重新设置字段 t2.do2();// }
因此定义字段可以在构造函数中定义局部变量,通过特权方法作为读取和设置字段的方法,实例函数可以通过特权函数间接访问字段。