this指向详解

JavaScript 中的 this 是一个关键字,它在不同的情况下会指向不同的值。this 的取值是在函数(非箭头函数)被调用时确定的,而不是在函数被定义时确定的。

1.全局上下文中:

在全局上下文中,this 指向全局对象,在浏览器中通常是 window 对象。

  console.log(this) //window

 

2.函数中:

在普通函数中,this 的取值取决于函数的调用方式:

1).如果函数作为普通函数调用,this 指向全局对象(非严格模式下)或者 undefined(严格模式下)。

2).如果函数作为对象的方法调用,this 指向调用该方法的对象。

 function fn() {
        console.log('函数中的this', this) //window
    }
    fn()

    let obj = {
        fn: function () {
            console.log('对象中的函数this指向', this) //obj
        }
    }
    obj.fn()

 

3.箭头函数中:

箭头函数的 this 不会因为调用方式而改变,而是根据外层(函数或全局)作用域来决定。

1).如果箭头函数在全局作用域中,this 将指向全局对象。

2).如果箭头函数在其他函数内部,this 将指向最近一层非箭头函数的 this 的值,或者如果没有,则指向全局对象。

    let obj2 = {
        fn: () => {
            console.log('对象中箭头函数的this指向', this) //window
        }
    }
    obj2.fn()

    function fa() {

        let a = {
            fn: () => {
                console.log('函数里箭头函数的this指向', this) //{a: 1}
            }
        }
        a.fn()
    }
    fa.call({
        a: 1
    })

 

4.构造函数中:

当一个函数被用作构造函数(使用 new 关键字)时,this 指向新创建的实例对象。

    function Func() {
        this.a = '1',
            this.asthis = function () {
                console.log('构造函数的This', this)
                return this
            }
    }

    let obj3 = new Func()
    obj3.asthis()
    console.log(obj3 === obj3.asthis()) //true

 

5.事件处理函数中:

当函数作为事件处理函数被调用时,this 通常指向触发事件的元素。

    let div = document.querySelector('div')
    div.addEventListener('click', function () {
        console.log('点击事件的this指向', this) //<div id="div"></div>
    })

 

6.call()、apply()、bind()方法中:

可以使用 call()apply()bind() 方法显式地指定函数内部的 this 指向的对象。

//    (1) call() 方法:

    function fb(...params) {
        console.log('fb的this指向:', this)
        console.log('fb的参数', ...params)
    }
    fb.call({}, 1, 2, 3)

    // call() 方法是函数对象的一个方法,它可以在调用函数的同时指定函数内部 this 的值,并且可以传入多个参数列表。
    // 语法:func.call(thisArg, arg1, arg2, ...)
    // thisArg 是在调用函数时将被绑定到函数内部的 this 上下文的值,后续的参数则是传入函数的参数列表。


    //     (2)apply() 方法:

    function fc(...params) {
        console.log('fc的this指向:', this)
        console.log('fc的参数', ...params)
    }
    fc.apply({
        b: 1
    }, [4, 5, 6])

    // apply() 方法与 call() 类似,但它接受的参数是以数组的形式传入的。
    // 语法:func.apply(thisArg, [argsArray])
    // thisArg 是在调用函数时将被绑定到函数内部的 this 上下文的值,argsArray 是一个数组,其中包含了要传入函数的参数。


    //     (3)bind() 方法:

    function fe(...params){
        console.log('fe的this指向:', this)
        console.log('fe的参数', ...params)
    }
    fe.bind({c:2},1,5,8)()

    // bind() 方法不会立即执行函数,而是返回一个新的函数,该函数的 this 值被绑定到 bind() 的第一个参数,其余的参数将作为固定参数传递给原函数。
    // 语法:newFunc = func.bind(thisArg, arg1, arg2, ...)
    // thisArg 是在调用新函数时将被绑定到函数内部的 this 上下文的值,后续的参数被视为固定参数,它们将会被传递给原函数。

 

posted on 2024-02-27 22:20  萬事順意  阅读(73)  评论(0编辑  收藏  举报