html 中綁定事件 this的指向

來源:互聯網
上載者:User

標籤:

var m=function(){

        alert(2);
    }
    var obj={
        A:function(){
        },
        m:function(){
            alert(3);
        },
        B:function(){
            var m=function(){
                alert(1);
            };
            var div=document.createElement("div");
            div.innerHTML="<p onclick=‘m();‘>xx</p>";
            document.body.appendChild(div);
        }
    };

    obj.B();

看起來好像onclick=m()會調用B函數裡頭定義的m函數,其實不會。這裡新增html,且是html行內觸發事件,所以函數執行在全域,m()調的是全域定義的m函數,結果彈出2,和B函數範圍一點關係都沒有。

(2)

潛在包含了一層匿名函數:

例一:

<p id="f" onclick="console.log(this)">1</p>,值為<p id="ff" onclick="console.log(this)">1</p>自己。

這裡相當於:

(p#f).onclick=function(){

console.log(this);

};

所以this當然是呼叫事件的p#f

例二:

<p id="f" onclick="function A(){alert(this==window);};A();">1</p>

相當於:

(p#f).onclick=function(){

function A(){alert(this==window);};

A();

};

所以A裡頭的this當然是window。

例三:

<p id="f" class="x" onclick="A(this)">1</p>
<script>
        var A=function(m){
            alert(m.className);       //點擊彈出"x"
        };
</script>

這裡相當於:

p#f.onclick=function(){

A(this);

};

function體裡的this必然是#f元素對象,所以可以彈出m.className。。

例四:

var m=function(){
            alert(10);
        }
        var obj={
            B:function(){
                var m=function(){
                    alert(1);
                };
                var div=document.createElement("div");
                div.innerHTML="cutemurphy";
                div.id="gg";
                document.body.appendChild(div);
                document.getElementById("gg").addEventListener("click",m,false);
            }
        };
        obj.B();      // 1

這個結果恰好和行內執行事件的結果相反,這裡會彈出1,而非10。因為它的m函數並非去全域找,而是按照普通的函數範圍鏈來尋找。。。理論支援是函數執行在定義的範圍裡。

例五:

var obj={
        A:function(){
            console.log(this);
        },
        B:function(){
            var m=function(){
                alert(1);
            };
            var div=document.createElement("div");
            div.innerHTML="<p id=‘xx‘>xx</p>";
            document.body.appendChild(div);
            var xNode=document.getElementById("xx");
            xNode.addEventListener("click",this.A,false);
        }
    };
    obj.B();     // xNode;

這裡很有意思,addEventListener裡的this.A的this指的是obj,而this.A的函數體function(){console.log(this)}裡的this又是xNode。

 

參考:

http://www.cnblogs.com/snandy/archive/2011/03/07/1976317.html

html 中綁定事件 this的指向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.