JS高级(二)

55 阅读1分钟

call和apply

1、call可以让一个函数的this临时指定成任意对象进行调用,apply功能同样

let obj = {}
function test() {
    this.xxx = 'test'
}
// obj.test() 无法直接调用
test.call(obj) // 这样就可以调用

let obj2 = {
    name: 'cuicui'
    age: 15
}
function test2() {
    console.log(this)
    console.log(this.name)
}
test2.call(obj2) // this会显示obj2的内容,this.name会打印cuicui

2、不同点

call需要使用逗号分隔列出所有参数

apply把所有参数写在数组里面。

(需要注意的是即使只有一个参数,也必须写在数组里面。)

let obj = {    name: 'cui'}function plus(n1, n2) {    this.a = n1    this.b = n2    console.log('plus为', this)}

plus.apply(obj, [100, 200]) // plus为 { name: 'cui', a: 100, b: 200 }

plus.call(obj, 200, 300) // plus为 { name: 'cui', a: 200, b: 300 }