一、this的指向分類
| 分類 | this指向 |
|---|---|
| 普通函式 | window |
| 建構式 | 實體物件,原型物件里面的方法也指向實體物件 |
| 物件方法 | 該方法所屬物件,若物件中的方法為普通函式寫法嗎,則this指向該方法所屬物件,若為箭頭函式,則this指向為window |
| 事件系結函式 | 系結事件物件 |
| 定時器 | window |
| 立即執行函式 | window |
| 箭頭函式 | 外層作用域中的this(且this指向不可改變) |
二、改變函式內部this指向
1.函式名稱.call(this要指向的,傳遞的引數1,...)
-
呼叫函式,并改變this指向,
var obj = { name: 'zs', age: 18 } function fn (a, b) { console.log(this) // this指向obj這個物件 console.log(a + b) // 6 } fn.call(obj, 1, 5)
2.函式名.apply(this要指向的,[傳遞的引數1,...])
-
呼叫函式,并改變this指向,傳遞的引數必須是陣列,
var arr = [1, 88, 0, 34, 171, 23] // 利用apply傳遞陣列(偽陣列),借助數學內置物件求陣列最大值/最小值 var max = Math.max.apply(Math, arr) console.log(max) // 171 var min = Math.min.apply(Math, arr) console.log(min) // 0
3.函式名.bind(this要指向的,傳遞的引數1,...)
-
不呼叫函式,但改變this指向,呼叫需要fn.bind(...)( ),
<button>按鈕1</button> <button>按鈕2</button> <button>按鈕3</button> <script> // 獲取所有的按鈕元素 let btns = document.querySelectorAll('button') for (let i = 0; i < btns.length; i++) { btns[i].addEventListener('click', function () { // 點擊后禁用按鈕 this.disabled = true setTimeout(function () { // 2秒后解除禁用該按鈕 this.disable = false }.bind(this), 2000) }) } </script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533548.html
標籤:其他
