bind()在JavaScript中的用途是什么?


当前回答

除上述内容外,bind()方法还允许对象从另一个对象借用方法,而无需复制该方法。这在JavaScript中称为函数借用。

其他回答

另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。

var name = "sample";
function sample(){
  console.log(this.name);
}
var cb = sample.bind(this);

function somefunction(cb){
  //other code
  cb();
}
somefunction.call({}, cb);

我将从理论上和实践上解释bind

javascript中的bind是一种方法--Function.prototype.bind.bind是一个方法。它是在函数原型上调用的。此方法创建一个函数,其主体与调用该函数的函数相似,但“This”引用传递给绑定方法的第一个参数。其语法为

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

示例:--

  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;

简单的例子

function lol(second, third) {
    console.log(this.first, second, third);
}

lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"

lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"

lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"

const newLol = lol.bind({first: '1'}); 
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"

const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"

const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"

我没有读过上面的代码,但我学到了一些简单的东西,所以我想在这里分享一下bind方法,我们可以将它用作任何普通方法。

<pre> note: do not use arrow function it will show error undefined  </pre>

让solarSystem={太阳:“红色”,moon:“白色”,sunmoon:函数(){let dayNight=this.sun+'是太阳的颜色,在白天呈现,'+this.moon+'是月亮的颜色,晚上呈现';返回日夜间;}}让工作=功能(工作,睡眠){console.log(this.sunmoon());//访问solatSystem直到现在都显示错误undefine suncommon,因为我们无法直接访问我们使用的.bind()console.log('我在'+work+'中工作,在'+sleep中睡眠);}let outPut=work.bind(solarSystem);outPut(“日”,“夜”)

bind()的最简单用法是生成一个函数,无论它是如何被调用的。

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

有关详细信息,请参阅MDN Web Docs上的此链接:

函数.product.bind()