call的作用是什么,为什么要使用它?

发布于:2025-05-27 ⋅ 阅读:(38) ⋅ 点赞:(0)

call() 的使用场景:

1)调用父级构造函数

当我们创建多个构造函数,而他们之间有较多的共同点,可以把共同点提炼出来成为一个父级构造函数,再分别在子级构造函数中继承它,就不用多次写这些属性或方法,且可以在需要的时候统一修改公共部分。

function Product(name, price){
    this.name = name;
    this.price = price;
    console.log('this.name', this.name)
    console.log('this.price', this.price)
    console.log('this.category', this.category)
}
 
// 调用父构造函数的call方法来实现继承
function Food(name, price){
    this.category = 'food';
    Product.call(this, name, price);
}
 
function Toy(name, price){
    this.category = 'toy';
    Product.call(this, name, price);
}
 
var cheese = new Food('hamburger', 15); // 会打印出 hamburger 15 food
var fun = new Toy('robot', 40); // 会打印出 robot 40 toy
// 将this指定为Food或Toy,新category 和旧name/price 都会存在
2)调用匿名函数

使用call来调用匿名函数的主要原因是为了改变函数的执行上下文(this的指向)‌。在JavaScript中,函数的this值是由其调用方式决定的。当使用call方法时,可以明确指定函数执行时的this值,这对于匿名函数尤其有用,因为匿名函数通常没有固定的this上下文。

假设有一个对象obj和一个匿名函数fn,我们希望在调用fn时,其内部的this指向obj。这时可以使用call方法:

var obj = {
    name: 'John',
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};
var fn = function() {
    console.log(this.name);
};
fn.call(obj); // 输出: Hello, John
3)调用函数并指定this,改变this的指向,传递参数给函数:
var person = { name: 'Alice' };
var greet = function(greeting) {
    console.log(greeting + ', ' + this.name);
};
greet.call(person, 'Hi'); // 输出: Hi, Alice

在上述示例中,我们定义了一个对象 person 和一个匿名函数 greet。通过使用fn.call(obj),我们改变了匿名函数执行时的上下文,使其内部的this指向 person 对象。这样,匿名函数就可以访问和操作 person 对象的属性了。此外,通过传递参数,我们进一步展示了call方法的灵活性和实用性。

传第一个参数指定this,直接调用的话this指向window全局对象,
call不传参也一样指向全局 fn.call(), 严格模式下 this是 undefined

网站公告

今日签到

点亮在社区的每一天
去签到