call方法,apply方法,和arguments对象

//1.call方法
// 2.apply方法
// 3.arguments对象


function add(a, b){
    console.log(a + b);
}

add(1, 2);
// call方法第一个参数是this指针,即调用者,第二个参数开始,就是原函数的实际参数
add.call(null, 10, 20);
// apply方法第一个参数是this指针,即调用者,第二个参数是一个数组,把实际参数打包放在数组里
add.apply(null, [100, 200]);

function info(hight, weight){
    console.log(`${hight}:${weight}`);
    // console.log(`${name}:${age}`);
    console.log(`${this.name}:${this.age}`);
}

name = 'zhangsan';
age = 20;
// info();  // console.log(`${name}:${age}`);  res为  undefined:undefined
info();  // console.log(`${this.name}:${this.age}`);  res为  zhangsan:20

let user = {
    name: 'lisi',
    age: 30
}
// info.call(user);  // console.log(`${this.name}:${this.age}`);  res为  lisi:30
// info.apply(user);  // console.log(`${this.name}:${this.age}`);  res为  lisi:30


info.call(user,160, 50);
info.apply(user, [160, 50]);


// 3.arguments对象   arguments 类似于一个类数组对象:// 当函数参数不确定时,使用 apply 和 arguments 配合使用。
function test(){
    let user = {
    name: 'lisi',
    age: 30
    }
    info.apply(user, arguments);
}

test(160, 50);
posted @ 2024-01-26 12:30  __username  阅读(7)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。