26. 面向对象进阶「this的处理和应用」

JS 中 THIS 的五种情况梳理

1. 事件绑定

2. 函数执行(包含自执行函数)

3. new 构造函数

  • new 执行,浏览器会在当前上下文默认创建一个对象(实例对象)。

  • 在初始化 this 的时候,会让 this 指向这个实例对象。代码中编写 this.xxx = xxx 都是给实例对象设置私有属性。

function Fn(x, y) {
    let total = x + y
    this.x = x
    this.y = y
}
const fn = new Fn(1, 2)
复制代码

4. 箭头函数

  • 箭头函数:箭头函数中没有自己的 this,所用到的 this 都是所处上下文中的 this
const obj = {
    n: 1,
    fn() {
        setTimeout(() => {
            console.log(this.n++)
        }, 1000)
    }
}
obj.fn()
复制代码

5. call / apply / bind

  • 都是用来改变 this 指向的,以后函数执行调用这三个方法就可以实现 this 的改变。

  • call / apply 都是立即执行函数,并且改变函数中的 this,再并且给函数传递参数信息。

  • call 方法

    • 在非严格模式下,context 不传递或者传递 null / undefined,则 this 都改为 window;严格模式下,不传是 undefined,否则传递谁,this 就改为谁;
    function fn(x, y) {
        console.log(this, x, y)
    }
    fn.call(10, 20) // this => Number{20} x => 20 y => undefined
    复制代码
    const obj = {
        name: '成健'
    }
    function fn() {
        console.log(this.name) // 成健
    }
    fn.call(obj)
    复制代码
  • apply 方法

    • apply 需要把所有需要传递的参数信息放在一个数组中
    const obj = {
        name: '成健'
    }
    function fn(x, y) {
        console.log(this.name) // 成健
        console.log(x, y) // 100, 200
    }
    fn.apply(obj, [100, 200])
    复制代码
  • bind 方法

    • 并不会把函数立即执行,它是预先处理函数中的 this 和 参数

    • 需求:点击 body 的时候,把 fn 执行,并且让 this -> obj,并且传递 10 / 20 给 x / y

    const obj = {
        name: '成健'
    }
    function fn(x, y) {
        console.log(this.name) // 成健
        console.log(x, y) // 100, 200
    }
    document.body.onclick = fn.bind(obj, 10, 20)
    复制代码

tips:补充知识点

  • call 的性能要比 apply 好一些「一丢丢」 尤其是传递三个及以上参数的时候。

  • 获取数据中的最大值

const arr = [10, 13, 24, 15, 26, 34, 11]
const max = Math.max.apply(Math, arr)
console.log(max) // 34
复制代码
  • 需求:任意数求和「把传递进来的实参(不固定个数)进行求和」
function sum(...params) {
    // params -> 数组,存储传递的所有实参
    return params.reduce((result, item) => {
        return result + item
    })
}
const total = sum()
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享