JavaScript中call()、apply()、bind()的区别以及手写apply

call()、apply()、bind()是用来改变this的指向的。

一、call和apply

直接举例子:


var cat = {
    
    
  name:"喵喵",
  eatFish:function(param1,param2){
    
    
    console.log("吃鱼");
	console.log("this的指向=>");
	console.log(this);
	console.log(param1,param2);
  }
}
 
var dog = {
    
    
	name:"汪汪",
	eatBone:function(param1,param2){
    
    
		console.log("啃骨头");
		console.log("this的指向=>");
		console.log(this);
		console.log(param1,param2)
	}


//第一种,用call方法
cat.eatFish.call(dog,"旺财-13岁","call");
//第二种,用apply方法,参数不一样
cat.eatFish.apply(dog,["旺财-13岁","apply"]);

在这里插入图片描述
如果call()和apply()的第一个参数是null或者undefined,那么this的指向就是全局变量,在浏览器里就是window对象。

二、bind

var eatFishFun = cat.eatFish.bind(dog,"旺财-13岁","bind"); //返回的是方法
eatFishFun();

在这里插入图片描述
bind()方法在这里再多说一下,bind的时候传的参数会预先传给返回的方法,调用方法时就不用再传参数了。

三、手写apply

function fn(a,b,c) {
    
     
      console.log(this);
      console.log(a,b,c);
     }
    Function.prototype.myApply= function(context){
    
    
      // 此处this为fn (谁调用了myApply谁就为fn)
       context.fn = this
      //  为apply所绑定的对象添加一个fn为function fn
       if(arguments[1]){
    
    
        //  判断是否有第二个参数 如果有则将参数解构传入到context.fn中 然后执行函数
        context.fn(...arguments[1])
       }
       else{
    
    
        // 如果没有直接执行函数
         context.fn()
       }
    }  
      fn.myApply({
    
    name:'29kun'},[1,2,3,4])

参考:https://blog.csdn.net/u010176097/article/details/80348447

猜你喜欢

转载自blog.csdn.net/weixin_44019523/article/details/114134090