call,apply和bind

231 阅读1分钟

call 和 apply ,bind之间的区别

  1. call 和 apply,bind都是改变this,但是call,是改变this指向,但是传参的形式是一个一个的传,而apply的传参的形式是以数组的形式传入。bind传参的形式也是一个一个传,但是bind是只绑定作用域,不执行函数,明白了其各自的特点就可以手写call,apply和bind的了
  2. 手写 call 方法
    var h = {
        name:'Tim',
        fn:function(a,b){
            console.log(a +b)
        }
    }
    var b = h.fn;
    b.call(h,1,2)
    // 手写call
    // 在跟函数上定义
   Function.prototype.myCall = function(xhr){
       xhr = xhr || window; //如果没有传入,则xhr默认为window
       xhr.fn = this  // xhr.fn = this   this = 调用的函数
    //    取得实参中的除第一位以外的数
       let arg = [...arguments].slice(1);
       
       let result = xhr.fn(...arg)
   }
   b.myCall(h,1,2)
  1. 手写bind
   Function.prototype.myBind = function(xhr){
       xhr = xhr || window; //如果没有传入,则xhr默认为window
       xhr.fn = this  // xhr.fn = this   this = 调用的函数
    //    取得实参中的除第一位以外的数
       let arg = [...arguments].slice(1);
       function result(){
           xhr.fn(...arg)
       }
       return result
   }
  1. 手写apply
 Function.prototype.myApply = function(xhr){
       xhr = xhr || window; //如果没有传入,则xhr默认为window
       xhr.fn = this  // xhr.fn = this   this = 调用的函数
    //    取得实参中的除第一位以外的数
       let arg = [...arguments].slice(1);
       xhr.fn(...arg[0])
   
   }