JavaScript apply使用

call 和 apply

  • 作用: 都是为了改变某个函数运行的context上下文而存在的,为了改变函数体内部 this的指向
  • JavaScript函数存在定义时上下文运行时上下文, 上下文(context)是可以改变的
  • callapply 作用完全一致,区别在于接收参数的方式不同
  • call的参数 fn.call(this,arg1,arg2)
  • apply的参数 fn.apply(this,[arg1,arg2])

demo

// 定义类
function Programmer(){}

// 添加原型
Programmer.prototype = {
    hobby : 'coding',
    say(){
        console.info(`I love ${this.hobby}`)
    }
}

// 原始调用
const xm = new Programmer()
xm.say()

// apply 调用
const xh = {hobby:'making love'}
xm.say.apply(xh)

Keep learning
原文地址:https://www.cnblogs.com/leslie1943/p/13363864.html