87,910
社区成员
发帖
与我相关
我的任务
分享
<script type="text/javascript">
function Rectangle(w,h){
this.width = w;
this.height = h;
}
alert(Rectangle(5,6));//undefined
var rect1 = new Rectangle(3.14,10);
alert(rect1);
alert(rect1.width);//?
alert(width);//?
</script>
function Rectangle(w, h) {
this.width = w;
this.height = h;
return this.width;
}
alert(Rectangle(5, 6));
2. rect1,是object,这个应该问题不大。
3. rect1.width 是3.14,这是因为new 之后返回一个实例,而构造函数中的this绑定到这个实例上,所以才会有3.14。
4. width 为什么是5,因为在前面,alert(Rectangle(5, 6)); 这句话的关系,如果没有明确的new,那么直接调用,那this就绑定到window上去了,所以width是5,其实也是this.width.
题外话:构造函数是js面向对象的基础,而由构造函数引出的继承又是js中的难点,所以多看看其它的相关教程,或许终能量变引起质变,早日入门。
以下两个链接,可做为扩展阅读。
http://kb.cnblogs.com/page/160908/
JS的构造函数