不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
再说Js构造函数
编辑:dnawo 日期:2009-07-17
复制内容到剪贴板
程序代码

function Rectangle(w,h)
{
this.width = w;
this.height = h;
return "mzwu.com";
}
{
this.width = w;
this.height = h;
return "mzwu.com";
}
上边构造函数和我们常见的构造函数稍有不同:有返回值,这对我们实例化对象有影响吗?测试一下:
复制内容到剪贴板
程序代码

var rectangle = new Rectangle(100,120);
alert(rectangle.width);
alert(rectangle.width);
结果完全正常[1],再做个测试:
复制内容到剪贴板
程序代码

alert(Rectangle(100,120));
结果显示"mzwu.com",这就和调用普通函数没区别了。
可以这么理解:当普通函数使用new关键字来实例化时,会有一个this对象被传进函数中,函数内可对这个对象进行处理,此时普通函数也称为构造函数。[2]
构造函数稍做修改:
复制内容到剪贴板
程序代码

function Rectangle(w,h)
{
this.width = w;
this.height = h;
return this.width;
}
alert(Rectangle(100,120));
{
this.width = w;
this.height = h;
return this.width;
}
alert(Rectangle(100,120));
等效于:
复制内容到剪贴板
程序代码

function Rectangle(w,h)
{
this.width = w;
this.height = h;
}
Rectangle(100,120);
alert(width);
{
this.width = w;
this.height = h;
}
Rectangle(100,120);
alert(width);
当函数作普通函数使用时,里边的this指的是window对象,当作构造函数用时,表示的是构造函数对象。
原型对象是构造函数特有的吗?
测试一下:
复制内容到剪贴板
程序代码

function Add(a,b)
{
return a+b;
}
alert(!!Add.prototype);
{
return a+b;
}
alert(!!Add.prototype);
结果:true,这说明任何函数都有原型对象,并非构造函数才有。
附
[1].《JavaScript权威指南》五版(P157)中说明:构造函数通常没有返回值。它们初始化作为this的值来传递的对象,并且没有返回值。然而,一个构造函数是允许返回一个对象值的,并且,如果它这么做,返回的对象成为new表达式的值。在此情况下,作为this的值的对象会被抛弃。
复制内容到剪贴板
程序代码

function Rectangle(w,h)
{
this.width = w;
this.height = h;
return {url:"mzwu.com"};
}
var rectangle = new Rectangle(100,120);
alert(rectangle.width);
alert(rectangle.url);
{
this.width = w;
this.height = h;
return {url:"mzwu.com"};
}
var rectangle = new Rectangle(100,120);
alert(rectangle.width);
alert(rectangle.url);
结果:

undefined
mzwu.com
mzwu.com
[2].《JavaScript权威指南》五版(P156)中对构造函数说明:new运算符的后面必须跟着一个函数调用。new创建了一个新的没有任何属性的对象,然后调用该函数,把新的对象作为this关键字的值传递。设计来和new运算符一起使用的函数叫做构造函数。
评论: 0 | 引用: 0 | 查看次数: 10832
发表评论
请登录后再发表评论!