函數(shù)的this
<script>
/*
this
- 函數(shù)在執(zhí)行時喧笔,JS解析器每次都會傳遞進一個隱含的參數(shù)
- 這個參數(shù)就叫做 this
- this會指向一個對象
- this所指向的對象會根據(jù)函數(shù)調用方式的不同而不同
1.以函數(shù)形式調用時帽驯,this指向的是window
2.以方法的形式調用時,this指向的是調用方法的對象
...
- 通過this可以在方法中引用調用方法的對象
*/
function fn() {
// console.log(this === window)
console.log("fn打印", this)
}
const obj = { name: "孫悟空" }
obj.test = fn
const obj2 = { name: "豬八戒", test: fn }
// fn()
// window.fn()
// obj.test() // {name:"孫悟空"}
// obj2.test() // {name:"豬八戒", test:fn}
const obj3 = {
name: "沙和尚",
sayHello: function () {
console.log(this.name)
},
}
const obj4 = {
name: "唐僧",
sayHello: function(){
console.log(this.name)
}
}
// 為兩個對象添加一個方法书闸,可以打印自己的名字
obj3.sayHello()
obj4.sayHello()
</script>
箭頭函數(shù)的this
<script>
/*
箭頭函數(shù):
([參數(shù)]) => 返回值
例子:
無參箭頭函數(shù):() => 返回值
一個參數(shù)的:a => 返回值
多個參數(shù)的:(a, b) => 返回值
只有一個語句的函數(shù):() => 返回值
只返回一個對象的函數(shù):() => ({...})
有多行語句的函數(shù):() => {
....
return 返回值
}
箭頭函數(shù)沒有自己的this尼变,它的this有外層作用域決定
箭頭函數(shù)的this和它的調用方式無關
*/
function fn() {
console.log("fn -->", this)
}
const fn2 = () => {
console.log("fn2 -->", this) // 總是window
}
// fn() // window
// fn2() // window
const obj = {
name:"孫悟空",
fn, // fn:fn
fn2,
sayHello(){
console.log(this.name)
function t(){
console.log("t -->", this) // window
}
t()
const t2 = () => {
console.log("t2 -->", this) // obj
}
t2()
}
}
// obj.fn() // obj
// obj.fn2() // window
obj.sayHello()
</script>