JavaScript中this的一些怪异现象

 <!--JavaScript伪协议和内联事件对于this的指向不同-->
    <a href="#" onclick="alert(this.tagName);">click me</a><!--弹出A-->
    <a href="javascript:alert(this.tagName);">click me</a><!--弹出undefined-->
    <a href="javascript:alert(this==window);">click me</a><!--弹出true-->

    <input id="btn" type="button" value="this demo" name="button"/>

 

<script type="text/javascript">
       
        var name = 'somebody';
        var angela = {
            name: 'angela',
            say: function () {
                alert("I'm " + this.name);
            }
        };
        var btn = document.getElementById('btn');

        //setTimeout和setInterval也会改变this的指向
        /*
        angela.say();//I'm  angela
        setTimeout(angela.say, 1000);//I'm  somebody
        setInterval(angela.say, 1000);//I'm  somebody
        */

        //on...也会改变this的指向
        /*        
        angela.say();//I'm  angela
        btn.onclick = angela.say;//I'm  button
        */

        //匿名函数调整this指向
        setTimeout(function () { angela.say(); }, 1000);//I'm  angela
        setInterval(function () { angela.say(); }, 1000)//I'm  angela
        btn.onclick = function () { angela.say(); };//I'm  angela
        setTimeout(function () { alert(this == window); }, 1000);//true
        btn.onclick = function () { alert(this == btn); }//true


        //call 和 apply调整this的指向
        angela.say.call(btn);//I'm  button
        setTimeout(function () { angela.say.call(btn); }, 1000);//I'm  button
        setTimeout(function () { angela.say.apply(btn); }, 1000);//I'm  button
        btn.onclick = function () { angela.say.apply(btn); }//I'm  button




        //将this指向的对象保存到变量
        var name = 'migo';
        var mydemo = {
            name: 'angela',
            say: function () {
                alert("I'm " + this.name);
            },
            init: function () {
                var that = this;
                document.getElementById('btn').onclick = function () {
                    that.say();//I'm angela
                    this.say();//这儿报错 this.say is not function
                }
            }
        };
    </script>
posted @ 2015-05-24 07:36  静逸  阅读(638)  评论(1编辑  收藏  举报