this

一、this指向

1、普通函数中this指向window

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

2、对象中调用函数,this指向调用函数的对象。如果先对函数作赋值,那么调用函数的变量对象时,this指向window。

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

3、构造函数中,this指向实例出来的对象

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

4、call、apply、bind中this指向第一个参数

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、箭头函数中this指向调用这个函数的外层对象

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

二、箭头函数的缺点

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、构造函数中不能使用箭头函数

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

三、箭头函数优点

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指向外层对象

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容