关于对象化编程的语句 现在我们有实力学习以下关于对象化编程,但其实属于上一章的内容了。
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 用法:
...
...
...
...
这个用法常用于立刻检测表单输入的有效性。
自定义构造函数 我们已经知道,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 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');
从这个构造函数我们不但看到了参数的用法,还看到了不同的属性用不同的数据型是可以的(上例五个属性分别为:字符串,布尔值,数字,日期,字符串),还看到了构造函数里也可以用构造函数来“构造”属性。如果用了足够的“保护措施”来避免无限循环,更可以用构造函数自身来构造自己的属性。