call apply bind the difference

Today's technology point -call apply bind the difference

Introduction

To think deeply call, apply, bind, and this function will now understand

this

this is our daily principal object code calls the function

for example:

    var obj = {
        foo: function(){
            console.info("this===>",this)
        }
    }
    var bar = obj.foo
    obj.foo()   // f打印出的this 就是obj
    bar()       //  打印出的this 就是window
    // 简单来讲就是谁调用函数this就指向谁

Then call the usual way and the difference between those functions and link it

  • As a function call myFun (a, b)
  • Call obj.objFun as an object method ()
  • As a constructor call let Bar = new Animal ( "cat")
  • Call the function as a method of myFun.call (content, a, b)
    Generally, we will be very familiar with the first three in the way, but the last myFun.call (content, a, b) is normal to call the form (basic form), the foregoing manner in this way are packaged syntactic sugar;
  //myFun(a,b) ---> myFun.call(undefined,a,b);
  //obj.objFun() ---> obj.objFun.call(obj);
  因此this也就是我们上面式子中的content-->call的第一个参数

Similarities and differences of the three call apply bind

Same point
  • It can be used to change the point of this issue
  • The first three parameters are pointing to this object, which is specified context (content)
  • All three can take advantage of subsequent incoming parameters
difference
  • The return value is a new bind function, plus calls to be executed
  • bing method creates a new function called binding function
  • bind the corresponding function return, to facilitate later call; the calls are immediately call and apply
  • call is directed to a known, gradually transferred to the subsequent parameter is an array of convenient parameters apply when the way
bind
  • bind () method creates a new function () is called, this bind this new function is the first parameter specifies the bind, the rest of the parameters used to call as an argument for the new function.
var module = {
  x: 42,
  getX: function() {
    console.log('this', this)
    return this.x;
  }
}

var unboundGetX = module.getX;

console.log(module.getX)  // 直接是对函数的引用, this没有指定,this 为 window
console.log(module.getX()) // 使用对象module调用函数,所以this就是module
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

var boundGetX = unboundGetX.bind(module);  
console.log(boundGetX());
// expected output: 42
call
  • When the role call of nothing more than a method of execution time want to be able to use another object as the object scope of it, in short, it is when I perform A method of hope in the form of arguments passed to B pass in a subject, a method for the scope of the object of the object B is replaced
  // 定义: 调用一个对象的方法,以另一个对象作为当前对象
  // call的使用方法
  // call修改的方式采用的是代入法
  //父类 Person        
  function Person() {            
    this.sayName = function() { 
      return this.name;
    }        
   }        
   //子类 Chinese        
   function Chinese(name) {  
      //借助 call 实现继承            
      Person.call(this); 
      this.name = name; 
      this.ch = function() { 
        alert('我是中国人');           
      }                     
   }        
   //测试        
   var chinese = new Chinese('成龙'); // 调用 父类方法
   console.log(chinese.sayName());   //输出 成龙
apply
  • Let us apply the method to build an array of parameters to the calling function, it also allows us to select the value of this
  • apply accepts two arguments, the first is to bind to this value, the second is an array of parameters
  • When the first argument is null, undefined, the default point window
    // apply的方法
    function add(a, b) {
        this.a = a;
        this.b = b;
        this.alert = function () {
            alert(this.a + this.b)
        }
    }
    function test() {
        add.apply(this, [5, 5]) //这里可以理解为 test函数中this等于add函数中的this
    }
    var c = new test()
    c.alert() //10

Scenarios

In our daily development, perhaps not very used to a lot of small partners or rarely used, in fact, they have a lot of use tips

  • Maximum and minimum data file tools
  let basicTools = {
      arrMaxOrMin:function(type,arr){
          let result = Math[type].apply(null,arr);
          return result;
      }
  }
  console.info("最大值",basicTools.arrMaxOrMin("max",[1,2,3]))  // 输出为3
  console.info("最小值",basicTools.arrMaxOrMin("min",[1,2,3]))  // 输出为1
  • An array of additional simple data types
  let basicTools = {
      arrAppendItem:function(arr1,arr2){
          return arr1.push.apply(arr1,arr2);
      }
  }

To help make learning easy, efficient and free for everyone to share a large number of resources to help you in becoming a full stack engineers, architects and even the way through the clutter. We are here to recommend a full-stack Learning Exchange front-end circle: ?? 947,552,909, or wx:.? Fxq1221623 welcome everyone into the group discussions and exchange learning exchanges and common progress?.

Some people are passionate about learning, but the lack of direction, and in the vast ocean of knowledge in the seemingly endless, at this time the most important thing is to know which technologies need to focus grasp, avoid doing useful work, the limited energy and to maximize state of.

Finally wish all encounter a problem and do not know how to do the front-end programmers, I wish you all in the future work and interview all the best.

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/104160854