首页 > 语言 > JavaScript > 正文

JavaScript入门教程(12) js对象化编程

2024-05-06 14:16:10
字体:
来源:转载
供稿:网友
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 版本
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选