What is the use of the JavaScript 'bind' method?

后端 未结 19 1938
自闭症患者
自闭症患者 2020-11-21 06:24

What is the use of bind() in JavaScript?

19条回答
  •  鱼传尺愫
    2020-11-21 06:48

    I will explain bind theoretically as well as practically

    bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is

         var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
    

    Example:--

      var checkRange = function(value){
          if(typeof value !== "number"){
                  return false;
          }
          else {
             return value >= this.minimum && value <= this.maximum;
          }
      }
    
      var range = {minimum:10,maximum:20};
    
      var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
      var result = boundedFunc(15); //passing value
      console.log(result) // will give true;
    

提交回复
热议问题