JavaScript中的call()方法是用于调用函数并指定函数中的this值的方法。通过call()方法,可以改变函数运行时的上下文,即改变函数内部的this指向。
call()方法的语法为:
function.call(thisArg, arg1, arg2, ...)
参数说明:
thisArg:在函数运行时被指定为函数体内this的值。arg1, arg2, ...:函数运行时传入函数的参数。
下面是一些关于call()方法的详细解析和代码实例:
- 改变函数内部的this指向:
const person = {
name: 'Alice',
sayHi: function() {
console.log(`Hi, my name is ${this.name}`);
}
};
const anotherPerson = {
name: 'Bob'
};
person.sayHi(); // output: Hi, my name is Alice
// 使用call()方法将person的sayHi()方法中的this指向anotherPerson对象
person.sayHi.call(anotherPerson); // output: Hi, my name is Bob
- 将类数组对象转换为数组:
function sum(a, b) {
console.log(a + b);
}
const numbers = {
0: 1,
1: 2,
len

最低0.47元/天 解锁文章
2043

被折叠的 条评论
为什么被折叠?



