关于this对象

<!DOCTYPE html>
<html>
<head>
    <title>关于this对象</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <script>
        function Person(username){
            var _self=this;
            this.username=username;
            /**
             * setTimeout是window的方法,所以setTime内调用this,也就是调用window,这里开发者经常弄混
             */
            setTimeout(function(){
                _self.showName();
            },1000);
        }
        Person.prototype.showName=function(){
            alert(this.username);
        }

        var mm=new Person('mm');


        window.onload=function(){
            var oBtn=document.getElementsByTagName('input')[0];
            var myData=new Data();
            /**
             * 此处不能直接 oBtn.onclick=myData.showData; 这样写会导入showData中this调用出错
             * 国为onclick事件是按钮触发的所有this=HTMLInputElement
             */
            oBtn.onclick=function(){
                myData.showData();
            };
        }

        function Data(){
            this.idx=1024;
        }
        Data.prototype.showData=function(){
            alert(this.idx);
        }
    </script>
</head>
<body>
    <input type=button value=查询 />
</body>
</html>

 

posted @ 2013-05-15 19:19  microsoft_kk  阅读(189)  评论(0编辑  收藏  举报