call 和apply的作用与区别

博客介绍了call和apply的作用与传参方式。二者共同作用是修改函数中this的指向,不传参时默认指向windows,有参数时this指向第一个参数。不同的是,call可将传给函数的参数分别作为自己的多个参数,apply则需将参数合并成数组作为一个参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先先说明它们共同的作用:call和apply 都是用来修改函数中this的指向问题;

其次就是它们不同的传参方式:注意上一句话中说他们的作用时有两个关键词 ‘函数’和‘this’,想要修改this 的指向,那么必然有一个this修改后的指向,而函数必然后关系到传参问题:call方法可以传给该函数的参数分别作为自己的多个参数,而apply方法必须将传给该函数的参数合并成一个数组作为自己的一个参数:

eg: 

var name = 'Evan';
var age = 20;
var person = {
    name: 'Hillary',
    age: 19,
    sayIntroduce: function () {
        return "Hello, My name is " + this.name + " and I'm " + this.age + ' years old.'
    },
    sayHobby: function (val1, val2) {
        return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
    }
}
var person1 = {
    name: 'Coy'
}
console.log(person.sayIntroduce()); // Hello, My name is Hillary and I'm 19 years old.

当我们通过 call 和 apply 来this的指向时,不传任何参数,则默认为将this指向修改为 windows

 // 当没有参数时,默认将this指向 window
 console.log(person.sayIntroduce.call()); // Hello, My name is Evan and I'm 20 years old.
 console.log(person.sayIntroduce.apply()); // Hello, My name is Evan and I'm 20 years old.

有参数时,this 指向第一个参数:

// 将this指向 person1,由于person1中没有age属性,因此为 undefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Coy and I'm undefined years old.
console.log(person.sayIntroduce.apply(person1)); // Hello, My name is Coy and I'm undefined years old.

当需要传递参数时,call可以直接写多个参数,apply需要用数组方式传递:

console.log(person.sayHobby.call(person1, 'swimming', 'hiking')); // I'm Coy, I like swimming and hiking.
console.log(person.sayHobby.apply(person1, ['swimming', 'hiking'])); // I'm Coy, I like swimming and hiking.

 

下面是一个构造函数的例子:

//构造函数应用
function Grade(max, min, average) {
    this.max = max;
    this.min = min;
    this.average = average;
}

function Subject(subjectName,max, min, average) {
    Grade.call(this, max, min, average);
    this.subjectName = subjectName;
}
var math = new Subject('math', 99, 60, 80);
console.log(math);

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_陌默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值