参考信息:<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>
以上js代码中共有两个“?”号,表示alert出来的值,它们分别是多少,如果执行一遍当然有结果!!我想知道为什么是这样?它们取值上到底有什么区别之处?
附:感谢各位大神参与回答,谢谢 javascript

解决方案 »

  1.   

    alert(rect1.width);//3.14
    alert(width);//5var rect1 = new Rectangle(3.14,10);
    方法里面的this指向rect1对象,所以alert(rect1.width);//3.14你第一次执行alert(Rectangle(5,6));
    方法里面的this指向window对象,alert(width)造价alert(window.width);,所以alert(width);//5  
      

  2.   

    1.? alert(rect1.width)=3.14 // new Rectangle(3.14,10)生成对象 this.width=3.14,this.height=10 2.? alert(width)=5 //Rectangle(5,6) 是这句设值的,
    这没有 new 实例Rectangle操作,就个普通的函数,默认它里头的 this==>window
    alert(width) 写成 alert(window.width)  也一样
      

  3.   

    就我个人的看法说一下,简单的说,就是两个作用域的事,复杂的说就是js的面向对象思想的一次顺流执行。
    1. Rectangle(5, 6) 这个为什么是undefined。
    因为function Rectangle(){}没有明确的 return,一般js认为没有明确return的就返回undefined.
    可以测试以下代码: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的构造函数