一、this 指向 window
1、全域函式里面的 this 指向 window
2、箭頭函式里面的 this 指向 window
// 定義全域變數 title 與函式 foo
var title = 'hello,world' // 注意:若使用 let 定義則不屬于全域變數
function foo() {
console.log(this.title)
}
function arrow() {
let title = 'hello,arrow'
return () => {
return () => {
console.log(this.title)
}
}
}
foo() // 輸出 hello,world 證明第 1 點
arrow()()() // 輸出 hello,world 證明第 2 點
3、事件系結函式里面的 this 默認指向 window
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="button" onclick="onTouchMe()">點我</button>
<script type="text/javascript">
var title = 'hello,world'
function onTouchMe() {
console.log(this.title) // 輸出'hello,world' 證明第 3 點
}
</script>
</body>
</html>
二、this 指向自身函式(物件)
1、new Foo().getTitle() 里面的 this 指向當前自身 Foo 建構式
2、obj.getTitle() 里面的 this 指向自身 obj 物件
以上兩點可理解為:誰呼叫我,this 環境就屬于誰,
class Foo{
constructor(title) {
this.title = title
}
getTitle() {
console.log(this.title)
}
}
// 輸出 Hello,world / Hello,Tony 證明第 1 點
const f1 = new Foo('Hello,world')
const f2 = new Foo('Hello,Tony')
f1.getTitle()
f2.getTitle()
// 輸出 hello,obj 證明第 2 點
let obj = {
title: 'Hello,obj',
getTitle() {
console.log(this.title)
}
}
obj.getTitle()
三、this 指向 undefined
1、嚴格模式下,this 指向 undefined
"use strict"
function getThis() {
console.log(this)
}
getThis() // 輸出 undefined 證明 第 1 點
四、setTimeout 里面的 this
1、普通函式 this 指向 window
2、箭頭函式的 this 指向上一層環境
var title = 'hello,world'
let obj = {
title: 'hello,obj',
getTitle() {
setTimeout(function() {
console.log(this.title)
})
}
}
obj.getTitle() // 輸出 hello,world 證明第 1 點
var title = 'hello,world'
let obj = {
title: 'hello,obj',
getTitle() {
// 此時里面的 console.log(this.title) 就相當于在這里訪問
// console.log(this.title)
setTimeout(() => {
console.log(this.title)
})
}
}
obj.getTitle() // 輸出 hello,obj 證明第 2 點
五、dom 事件系結里面的 this
1、事件系結里的 this 指向隨著函式系結環境而變,默認是 window
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="button" onclick="onTouchMe()">點我</button>
<script type="text/javascript">
var title = 'hello,world'
// 默認是 window
function onTouchMe() {
console.log(this.title) // 輸出'hello,world'
}
// ============================================
let obj = {
title: 'hello,obj',
onTouchMe() {
console.log(this.title) // 輸出 hello,obj'
}
}
// 隨函式系結環境而變
document.getElementById('button').onclick = obj.onTouchMe
</script>
</body>
</html>
六、改變 this 指向的三個方法:apply / call / bind
1、apply / call / bind
let a = {
title: 'Hello,world',
getTitle() {
console.log(this.title)
}
}
let b = {
title: 'Hello,Tony'
}
a.getTitle() // 正常輸出 Hello,world
a.getTitle.apply(b, ['引數1', '引數2']) // 將 this 環境指向 b ,輸出 Hello,Tony
a.getTitle.call(b, '引數1', '引數2') // 將 this 環境指向 b ,輸出 Hello,Tony
a.getTitle.bind(b)('引數1', '引數2') // 將 this 環境指向 b ,輸出 Hello,Tony
// 注意:bind 不能多次指向,因為第一次系結時環境就已經確認好了,
a.getTitle.bind(b).bind(a)() // this 環境依然屬于 b
好了,本文就到這里,希望本文的 this 情況對你有幫助,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/401658.html
標籤:其他
