2009年4月5日 星期日

JavaScript中的对象化编程

文章來源:http://www.ijavascript.cn/jiaocheng/javascript-object-programme-95.html

关于对象化程的语句 现在我们有实力学习以下关于对象化编程,但其实属于上一章的内容了。

with
语句 为一个或一组语句指定默认对象。

用法:

with (<象>) <句>;

with 语句通常用来缩短特定情形下必须写的代码量。在下面的例子中,请注意 Math 的重复使用:

x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10);

y = Math.tan(14 * Math.E);

当使用 with 语句时,代码变得更短且更易读:

with (Math) {

  x = cos(3 * PI) + sin(LN10);

  y = tan(14 * E);

}

this 对象 返回当前对象。在不同的地方,this 代表不同的对象。如果在 JavaScript 主程序中(不在任何 function 中,不在任何事件处理程序中)使用 this,它就代表 window 对象;如果在 with 语句块中使用 this,它就代表 with 所指定的对象;如果在事件处理程序中使用 this,它就代表发生事件的对象。


一个常用的 this 用法:

<script>

...

function check(formObj) {

  ...

}

...

</script>


<body ...>

...

<form ...>

...

<input type="text" ... onchange="check(this.form)">

...

</form>

...

</body>

这个用法常用于立刻检测表单输入的有效性。


自定义构造函数 们已经知道,Array()Image()等构造函数能让我们构造一个变量。其实我们自己也可以写自己的构造函数。自定义构造函数也是用 function。在 function 里边用 this 来定义属性。

function <构造函名> [(<参数>)] {

  ...

  this.<性名> = <初始值>;

  ...

}

然后,用 new 构造函数关键字来构造变量:

var <量名> = new <构造函名>[(<参数>)];

构造变量以后,<变量名>成为一个对象,它有它自己的属性—— this function 里设定的属性。


以下是一个从网上找到的搜集浏览器详细资料的自定义构造函数的例子:

function Is() {

  var agent = navigator.userAgent.toLowerCase();

  this.major = parseInt(navigator.appVersion);  //主版本

  this.minor = parseFloat(navigator.appVersion);//全版本

  this.ns = ((agent.indexOf('mozilla')!=-1) &&

             ((agent.indexOf('spoofer')==-1) && //是否 Netscape

              (agent.indexOf('compatible') == -1)));

  this.ns2 = (this.ns && (this.major == 3));    //是否 Netscape 2

  this.ns3 = (this.ns && (this.major == 3));    //是否 Netscape 3

  this.ns4b = (this.ns && (this.minor < 4.04)); //是否 Netscape 4 低版本

  this.ns4 = (this.ns && (this.major >= 4));    //是否 Netscape 4 高版本

  this.ie = (agent.indexOf("msie") != -1);      //是否 IE

  this.ie3 = (this.ie && (this.major == 2));    //是否 IE 3

  this.ie4 = (this.ie && (this.major >= 4));    //是否 IE 4

  this.op3 = (agent.indexOf("opera") != -1);    //是否 Opera 3

  this.win = (agent.indexOf("win")!=-1);        //是否 Windows 版本

  this.mac = (agent.indexOf("mac")!=-1);        //是否 Macintosh 版本

  this.unix = (agent.indexOf("x11")!=-1);       //是否 Unix 版本

}


var is = new Is();

这个构造函数非常完整的搜集了浏览器的信息。我们看到它为对象定义了很多个属性:major, minor, ns, ie, win, mac 等等。它们的意思见上面的注释。把 is 变量定义 Is() 对象后,用 if (is.ns) 这种格式就可以很方便的知道浏览器的信息了。我们也可以从这个构造函数中看到,它也可以使用一般的 JavaScript 语句(上例中为 var 语句)。


让我们再来看一个使用参数的构造函数:

function myFriend(theName, gender, theAge, birthOn, theJob) {

  this.name = theName;

  this.isMale = (gender.toLowerCase == 'male');

  this.age = theAge;

  this.birthday = new Date(birthOn);

  this.job = theJob

}


var Stephen = new myFriend('Stephen', 'Male', 18, 'Dec 22, 1982', 'Student');

从这个构造函数我们不但看到了参数的用法,还看到了不同的属性用不同的数据型是可以的(上例五个属性分别为:字符串,布尔值,数字,日期,字符串),还看到了构造函数里也可以用构造函数来构造属性。如果用了足够的保护措施来避免无限循环,更可以用构造函数自身来构造自己的属性。


沒有留言:

張貼留言