this關鍵字用法詳解
阿新 • • 發佈:2021-07-25
this關鍵字的使用方法
1.全域性環境輸出this,指向誰?
直接輸出this指向全域性物件
console.log(this) // 全域性window
2.全域性環境輸出this,指向誰?
全域性函式其實就是window(全域性物件)的方法
function fn(){
console.log(this)
}
fn() // window
3.物件的方法輸出this,指向誰?
this放在方法中,this指向呼叫這個方法的物件
let cat = { name:"喵喵", sayName(){ console.log("我是" + this.name) } } cat.sayName() // 我是喵喵
4.Dom事件輸出this,指向誰?
this放在dom事件中,this指向的是dom物件
<button>按鈕</button>
let btn = document.querySelector("button")
btn.onclick = function () {
console.log(this)
}
5.建構函式中的this,指向誰?
建構函式是用來建立物件的,就相當於f
function F(){ this.name = "小明" console.log(this) } let f = new F() console.log(f)
6.new關鍵字做了什麼?
new會建立物件,將建構函式中的this指向創建出來的物件
7.箭頭函式中的this,指向誰?
- 普通函式,誰呼叫指向誰,箭頭函式在哪裡定義指向誰
- 箭頭函式外指向誰就指向誰
- 箭頭函式中沒有this
三種說法
let cat1 = {
name: "喵喵",
sayName(){
setTimeout(() => {
console.log(this.name) // 喵喵
},1000)
}
}
cat1.sayName()