this

一、this指向

1、普通函數(shù)中this指向window

function test() {
    console.log(this) // window
}

2、對象中調(diào)用函數(shù),this指向調(diào)用函數(shù)的對象。如果先對函數(shù)作賦值,那么調(diào)用函數(shù)的變量對象時,this指向window。

let obj = {
    age: 18,
    say() {
        console.log(this)
    }
}
obj.say() // obj
let fn = obj.say()
fn() // window

3、構(gòu)造函數(shù)中,this指向?qū)嵗鰜淼膶ο?/p>

function Person(name) {
    this.name = name
    console.log(this) // Person {name: "xiaohong"}
}
let pp = new Person('xiaohong')

4、call、apply、bind中this指向第一個參數(shù)

let obj = {
    name: 'lisi',
    say(){
        console.log(this)
    }
}
let obj1 = {
    name: 'wangwu'
}
obj.say.call(obj1)  // {name: 'wangwu'}
obj.say.bind(obj1)()   // {name: 'wangwu'}

5、箭頭函數(shù)中this指向調(diào)用這個函數(shù)的外層對象

let obj2 = {
    name: 'wangwu',
    say: () => {
        console.log(this)
    }
}
obj2.say() // window

二、箭頭函數(shù)的缺點(diǎn)

1、沒有arguments

let obj3 ={
    // say: function()  { //[1,2]
    say = () =>  { // 報錯
        console.log(arguments)
    }
}
obj3.say(1,2)

2、原型鏈上不能使用

function Person(name, age) {
    this.name = name
    this.age = age
} 
Person.prototype.say = () => { // undefind
// Person.prototype.say = function() {
    console.log(this.name, this.age) // 'lisi', 18
}
let p = new Person('lisi', 18)
p.say()

3、構(gòu)造函數(shù)中不能使用箭頭函數(shù)

let Person = (name, age) => {
    this.name = name
    this.age = age
}
let p = new Person('zhangsan', 3)
console.log(p) // 報錯

4、call、apply、bind不能改變this指向

let obj5 = {
    name: 'lisi',
    say: () => {
        console.log(this)
    }
}
let obj6 = {
    name: 'wangwu'
}
obj5.say.call(obj6) // window

三、箭頭函數(shù)優(yōu)點(diǎn)

1、簡明語法

const l1 = [1,2,3,4,5]

const l2 = l1.map(function(i) {
    return i *2
})

console.log(l2) // [2, 4, 6, 8, 10]

const l3 = l1.map((i) => {
    return i *2
})

2、隱式返回

const l4 = l1.map((i) => {i *3})

3、this指向外層對象

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容