JavaScript中this的一些練習

來源:互聯網
上載者:User

標籤:IV   ons   相同   參數   ini   log   OLE   head   委託   

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>.father {width: 100px;height: 100px;background-color: red;}.child {width: 20px;height: 20px;background-color: yellow}</style></head><body><div class="father"><div class="child"></div></div><script src="jquery-1.11.2.min.js"></script><script>//on方法會向事件監聽的處理函數傳遞一個參數 event.target 處理函數內部的this指向// event.target 所以列印出來的this就是event.target 即<div class="child"></div>
// $(‘.child‘).on(‘click‘,function(){ // console.log(this); //<div class="child"></div> // })

//事件委託,首先按字面的意思就能看你出來,是將事件交由別人來執行, // 再聯想到上面講的事件冒泡,是不是想到了?對, // 就是將子項目的事件通過冒泡的形式交由父元素來執行。 // 事件委託不僅實現相同了功能,而且大大減少了DOM操作。
//監聽.father下的.child的點擊事件 // $(‘.father‘).on(‘click‘,‘.child‘,function(){ // console.log(this); //<div class="child"></div> // })  // $(‘.child‘)[0].on(‘click‘,function(){ // console.log(this);//<div class="child"></div> // })
var app={ init:function(){//init()裡面的this指的是app this.$father=$(‘.father‘);//給app這個對象綁定一個屬性$father this.$child=$(‘.child‘);//給app這個對象綁定一個屬性$child this.bind();//app.bind() }, bind:function(){ var _this=this;//this指的是app
//監聽.father點擊事件 監聽到click時 向this.sayHi傳遞了event.target //即.father的dom對象<div class="father"><div class="child"></div></div> this.$father.on(‘click‘,this.sayHi);
// 將_this.sayHello()改寫為_this.sayHello.call(_this) // sayHello在執行的時候 內部的this指向的app對象本身 this.$child.on(‘click‘,function(){ _this.sayHello(); })
//如果沒有bind(this),this.sayBye會接受到傳遞的event.target即.child的dom對象 // 但此時手動綁定了this 而綁定的this與拒收的this是一致的 指代的是app對象 this.$child.on(‘click‘,this.sayBye.bind(this)) }, sayHi:function(){ console.log(‘sayHi‘,this)//<div class="father"><div class="child"></div></div> }, sayHello:function(){ console.log(‘sayHello‘,this)//app }, sayBye:function(){ console.log(‘sayBye‘,this)//app } } app.init(); </script></body></html>

JavaScript中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.