JavaScript中this指向

一般调用函数的时候,我们需要确认函数内部的this指向问题

一般指向函数的调用者

总结一下不同函数调用方式对应的this指向

1 普通函数调用 fun() -------window      严格模式时this为undefined

2 构造函数调用 new Star() ------ 实例对象,原型对象里面的方法也指向实例对象

3 对象方法调用 ------ 该方法所属对象

4 事件绑定方法 ------- 绑定事件对象

5 定时器回调函数 ------ window

6 立即执行函数 -------- window

函数内部的this指向可以手动指定,主要有call(),apply(),bind()三种方法

1 call()

  语法: fun.call(that,arg1,arg2,...)

  功能:调用fun函数,改变fun函数的this指向

  主要应用: 可以用于构造函数的属性继承

function Father(uname.uage) {
    this.name = uname
    this.age = uage
}
function Son(uname,uage) {
    Father.call(this,uname,uage)
}
let son = Son(lldh,42)

2 apply()

  语法: fun.apply(that,[arg1,arg2,...]) 

 功能: 调用fun函数,改变fun函数内部的this指向

典型应用: 求数组的最大最小值

        let arr = [1,22,4,55,99,6]
        let max = Math.max.apply(Math,arr) // 99
        let min = Math.min.apply(Math,arr) // 1

3 bind()

bind也可以改变函数内部的this指向,当时与call,apply所不同的是,bind并不会调用函数

适用于要修改this指向但不用马上调用的场景,比如按钮的点击事件,定时器回调等

        let obj = {
            name: 'jsthin'
        }
        setTimeout(function(){
            console.log(this.name)  //jsthin
        }.bind(obj),2000)
原文地址:https://www.cnblogs.com/linhongjie/p/12154018.html