javascript中call的用法总结

本文详细介绍了JavaScript中call方法的应用场景,包括指定上下文的this、调用匿名函数及父构造函数等,帮助读者掌握call方法的正确使用。

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

javascript中call的用法总结

1.使用call方法调用函数并且指定上下文的’this’
function greet(){
    console.log(this.name+",age="+this.age)
}

greet.call({name:'lihh',age:24});//输出:lihh,age=24

可以看出greet.call中的{name:‘lihh’,age:24}就是greet()中的this

2.使用call方法调用匿名函数

下边是来自MDN的一个例子

var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];

for (var i = 0; i < animals.length; i++) {
  (function (i) { 
    this.print = function () { 
      console.log('#' + i  + ' ' + this.species + ': ' + this.name); 
    } 
    this.print();
  }).call(animals[i], i);
}

运行结果为#0 Lion: King
#1 Whale: Fail

可以看出的是:a.第一个animals[i] 替代了this,第二个i则是传递进去了参数

3.使用call方法调用父构造函数

MDN上的例子有点没看懂,所以改造了一下,在Food中打印一下this,看看要替代的到底是什么

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError(
      'Cannot create product ' + this.name + ' with a negative price'
    );
  }
}

function Food(name, price) {
  console.log('---');
  console.log(this);
  console.log('---');
  //Product.call(this, name, price);
  this.category = 'food';
}

然后new Food(‘青椒’,9),结构如下
//—
// Food(){}
// category:“food”
// proto:Object
//—
有点蒙,我的理解是Product.call(this, name, price);这句代码中的this是function Food(name, price) {},用此来替换Product中this的指向,name和price则用来给Product传递参数

4.总结以上三点,借鉴MDN的说明:
  • call的用法为func.call(thisArg,args…),thisArg用来替代func中的this指向,args则是给func设置参数
  • 3的做法似乎是一种喧宾夺主的做法,把Product中this改为Food的指向,从而达到子类继承父类的做法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值