JavaScript apply使用
call 和 apply
- 作用: 都是为了改变某个函数运行的context上下文而存在的,为了改变函数体内部this的指向
- JavaScript函数存在- 定义时上下文和- 运行时上下文, 上下文(- context)是可以改变的
- call和- apply作用完全一致,区别在于接收参数的方式不同
- 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

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号