函数,构造函数中使用call,apply,bind 以及他们的区别

函数中使用

bind

function eat(food,name){
  this.food=food
  this.call=call
}
function weather(food,name,what){
  console.log("今天的天气是"+what);
  console.log("我喜欢吃"+food);
  console.log("我是"+name)
}
weather.bind(eat,"肉","狗","大雨")()

在这里插入图片描述
call

function eat(food,name){
  this.food=food
  this.call=call
}
function weather(food,name,what){
  console.log("今天的天气是"+what);
  console.log("我喜欢吃"+food);
  console.log("我是"+name)
}
weather.call(eat,"肉","狗","大雨")

在这里插入图片描述
apply

function eat(food,name){
  this.food=food
  this.call=call
}
function weather(food,name,what){
  console.log("今天的天气是"+what);
  console.log("我喜欢吃"+food);
  console.log("我是"+name)
}
weather.apply(eat,["肉","狗","大雨"])

在这里插入图片描述

function eat(food,name){
  this.food=food
  this.call=call
}
function weather(food,name,what){
  console.log("今天的天气是"+what);
  console.log("我喜欢吃"+food);
  console.log("我是"+name)
}
weather.bind(eat,"肉","狗","大雨")()
weather.call(eat,"肉","狗","大雨")
weather.apply(eat,["肉","狗","大雨"])

在构造函数中使用

apply

function student(name,age) {
  this.name=name
  this.age=age
}
function person(name,age,grade) {
  this.grade=grade
  student.apply(this,arguments)
}
const a=new person("小明",18,"五年级")
console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);

在这里插入图片描述
但是用apply参数数组必须一致
在这里插入图片描述
call

function student(name,age) {
  this.name=name
  this.age=age
}
function person(name,age,grade) {
  this.grade=grade
  student.call(this,name,age)
}
const a=new person("小明",18,"五年级")
console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);

在这里插入图片描述
bind

function student(name,age) {
  this.name=name
  this.age=age
}
function person(name,age,grade) {
  this.grade=grade
  student.bind(this,name,age)()
}

const a=new person("小明",18,"五年级")

console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);

在这里插入图片描述

三者区别

虽然他们的作用都是改变this的指向,第一个参数都是你要改变的this的指向但是他们也有很b多不同点
1.call和apply是立即执行的
2.bind返回的是一个函数
3.apply的第二个参数是一个数组、
4.call除了第一个参数都是传入的参数
bind和call的方法传参方式一样但是返回的是函数想要执行必须以函数的方式执行

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

万事胜意sy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值