首页 > 其他分享 >js中的call,apply与bind

js中的call,apply与bind

时间:2022-11-06 22:02:47浏览次数:76  
标签:let name bind Dog Cat call apply

call,apply,bind都是一种方法。

一,call()

①:call() 是可以 调用函数的。

1 function fn() {
2   console.log(12)
3 }
4 
5 fn.call()   // 12

 

②:通过给call() 内部传参,可以改变 this指向。

 1 let Dog = {
 2   name: '旺财',
 3   sayName() {
 4     console.log(this.name)
 5   },
 6 }
 7 
 8 let Cat = {
 9   name: '喵喵',
10 }
11 
12 Dog.sayName.call(Cat)   //喵喵

③:如果给 call() 内部传递多个参数,那么第一个默认为 改变 this 的参数,后面为传给函数的参数。

 1 let Dog = {
 2   name: '旺财',
 3   sayName() {
 4     console.log(this.name)
 5   },
 6   eat(food1, food2) {
 7     console.log(this.name + '吃的食物是:' + food1 + ',' + food2)
 8   },
 9 }
10 
11 let Cat = {
12   name: '喵喵',
13 }
14 Dog.eat.call(Cat, '鱼', '骨头')
15 //喵喵吃的食物是:鱼,骨头

第十四行中call()的第一个参数,改变 this 指向,所以 this.name 为‘喵喵’,后面的连个参数为传递给 Dog中eat方法的参数。

二:apply()

apply() 与call() 类似,唯一的区别便是,在十四行传递参数时,后面的传递的参数写到了数组里面。

1 //call() 方法 传参数
2 Dog.eat.call(Cat, '鱼', '骨头')
3 
4 //apply()方法传参数
5 Dog.eat.apply(Cat, ['鱼', '骨头'])

三:bind()

bind()传递参数和call()方法一样,只是不会立即执行函数,而是会返回一个函数。

 1 let Dog = {
 2   name: '旺财',
 3   sayName() {
 4     console.log(this.name)
 5   },
 6   eat(food1, food2) {
 7     console.log(this.name + '吃的食物是:' + food1 + ',' + food2)
 8   },
 9 }
10 
11 let Cat = {
12   name: '喵喵',
13 }
14 let fn1 = Dog.eat.bind(Cat, '鱼', '骨头')
15  fn1()
16 //喵喵吃的食物是:鱼,骨头

 

大家只要牢记记住 call()方法怎么使用,然后小推一下就能明白 apply() 与bind()的用法了。

感谢观看!如果错误,还望指出。

标签:let,name,bind,Dog,Cat,call,apply
From: https://www.cnblogs.com/zy-feng/p/16864283.html

相关文章