JavaScript中this的一些怪異現象

靜逸發表於2015-05-24
 <!--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>

相關文章