this关键字

394 阅读1分钟

this关键字:表示当前对象(与使用场景有关)

this使用的几种场景

  • 在普通函数中
    • this指向window对象
    function fn1() {
        console.log(this);//指向window
        this.a = 10
    }
  • 在对象方法中
    • this指向调用方法的对象
    let obj = {
            a: 1,
            b: 2,
            fn: function () {
                console.log('对象方法中的this', this);//执行obj
            }
        }
        // obj.fn()
  • 在定时器中
    • 指向window对象
    <button>this</button>
    setTimeout(() => {
        console.log('定时器', this); //指向window
    }, 1000);

  • 在事件处理函数中
    • 指向事件源

    let btn =document.querySelector('button')
    btn.onclick=()=>{
        console.log(this);//指向事件源btn
    }
  • 自执行函数
    • 指向window对象
    let fn2 =(function () {
        console.log(this);//指向window
    })()

改变this指向

  • 改变this指向可以通过三种方式,分别是call,apply,bind

call

var obj = {
    name: 'jack',
    age: 23
}
function fn(a, b) {
    this.name = a
    this.age = b
    console.log(this);//{name: '小明', age: 20}
}
fn.call(obj, '小明', 20)//指向obj

apply

var obj = {
    name: 'jack',
    age: 23
}
function fn(a, b) {
    this.name = a
    this.age = b
    console.log(this);//{name: '小明', age: 20}
}
fn.apply(obj, ['小明', 20])//指向obj

bind 会返回一个新函数

var obj = {
    name: 'jack',
    age: 23
}
function fn(a, b) {
    this.name = a
    this.age = b
    console.log(this);//{name: '小明', age: 20}
}
var newFn = fn.bind(obj, '小明', 20)//指向obj
newFn()

call、apply、bind 异同点

  • call和bind传参方式相同
    • call和bind是直接传参
  • call和apply传参方式不同
    • apply 传参是传入一个数组
  • call和apply不会返回一个新函数,bind会返回一个新的函数,通过调用这个函数才能实现相应的功能

箭头函数中的this问题

  • 箭头函数中没有this,里面的this指向上下文(调用对象所在的对象)

构造函数中的this

  • 指向被创建出来的对象
  • new 关键字的作用,将构造函数中的this指向被创建出来的对象

总结

  • this的指向遵从谁调用就指向谁的原则