call, apply , bind 区别详解 及 实现购物车业务开发实例

call 方法:

原理

call 方法允许一个对象借用另一个对象的方法。通过 call,你可以指定某个函数运行时 this 指向的上下文。本质上,call 改变了函数运行时的作用域,它可以让我们借用一个已存

在的函数,而将函数体内的 this 绑定到当前对象。

function displayInfo(age, job) {
    console.log(`${this.name} is ${age} years old and is a ${job}.`);
}

const person = {
    name: 'Alice'
};

// 使用 call 调用函数,同时将 this 设置为 person 对象
displayInfo.call(person, 30, 'developer');
// 输出: Alice is 30 years old and is a developer.

apply方法:

原理

applycall 非常相似,差别仅在于 apply 接受一个参数数组,而不是一组参数列表。这在你需要传递一个数组数据作为调用函数的参数时特别有用。比如,当你使用 Math.max() 计算数组中的最大值时,可以使用 apply

function displayInfo(age, job) {
    console.log(`${this.name} is ${age} years old and is a ${job}.`);
}

const person = {
    name: 'Alice'
};

// 使用 apply 调用函数,传递参数数组
displayInfo.apply(person, [30, 'developer']);
// 输出: Alice is 30 years old and is a developer.

bind方法:

bind 方法创建一个新的函数,当被调用时,这个新函数的 this 被指定为 bind 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

function greet(greeting, punctuation) {
    console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

const person = { name: 'Alice' };
const sayHello = greet.bind(person, 'Hello');
sayHello('!');  // 输出: Hello, my name is Alice!

原理解析

  • callapply 的区别 主要在于参数的传递方式。call 需要将参数按顺序一个接一个地传递,而 apply 则是把参数放在一个数组中传递。
  • bind 则是返回一个新的函数,允许你预设 this 参数和其他参数,之后可以随时调用。

这三个方法都是函数原型上的方法,即 Function.prototype,因此在JavaScript中所有函数都可以使用这些方法。这些方法的主要用途是控制函数执行时 this 关键字的值。

代码:

//商品购物车 套版  函数
function ShoppingCart(){
  this.items = []
  this.total = 0
  //this.total = items.length ?

}
//如果需要后续绑定this 对象,谨慎用箭头函数 (call,bind,apply 影响不了他的this)
ShoppingCart.prototype.addItem = function (item){
  this.items.push(item)
  this.total += item.price
  console.log(`${item.name} add successfully . Total is ${this.total}`)
}
ShoppingCart.prototype.removeItem = function (itemName){
  const itemIndex = this.items.findIndex(item => item.name === itemName)
  if(itemIndex > -1){
    this.total -= this.items[itemIndex].price
    this.items.splice(itemIndex,1)
    console.log(`${itemName} remove successfully.Total is ${this.total}`)
  }
}
//使用call 、apply
const p1 = {
  name:'书包',
  price:221
}
const p2 = {
  name:'书',
  price:12
}
const cart = new ShoppingCart()
//call适合一个对象 ,apply适合数组对象(必须是一个数组)
//两者都只会临时更改对象一次this 指向方向
cart.addItem.call(cart,p1)
cart.addItem.apply(cart,[p1, p2])
//bind 方法
const gadget = { name: 'Echo Dot', price: 49.99 }
// 创建一个永久绑定到 cart 的 addItem 方法
const boundAddItem = cart.addItem.bind(cart)
// 添加商品
boundAddItem(gadget)

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值