js中的call,apply与bind

  • js中的call,apply与bind已关闭评论
  • 103 次浏览
  • A+
所属分类:Web前端
摘要

call,apply,bind都是一种方法。一,call()①:call() 是可以 调用函数 的。 ②:通过给call() 内部传参 ,可以改变 this指向 。

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()的用法了。

 

实际应用场景: 

可以通过 this 的指向,进行函数方法的继承 .可以进行单个或者多个继承。

 1 function Animal() {  2   this.say = function () {  3     console.log('我能说话')  4   }  5 }  6 function Fly() {  7   this.fly = function () {  8     console.log('我能飞')  9   } 10 } 11  12 function Cat() { 13   // Cat 的this指向为cat 14   Animal.call(this) 15   //Animal 中的 this 指向也为 cat 16   Fly.call(this) 17 //同理 Fly中的 this 也指向了 cat 18 } 19 let cat = new Cat() 20 cat.say() 21 cat.fly()

 

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