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


当前回答

简单的例子

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()方法将对象作为第一个参数,并创建一个新函数。当调用函数时,函数体中this的值将是在bind()函数中作为参数传入的对象。

这在JS中是如何工作的

javascript中this的值始终取决于调用函数的对象。此值始终指调用函数的点左侧的对象。对于全局范围,这是窗口(或nodeJS中的全局)。只有调用、应用和绑定才能以不同方式更改此绑定。下面是一个示例,说明this关键字的工作原理:

让obj={prop1:1,func:function(){console.log(this);}}obj.func();//obj位于点的左侧,因此这是指obj常量customFunc=obj.func;//我们将函数存储在customFunc对象中customFunc();//现在点左边的对象是窗口,//customFunc()是window.customFunc(//因此,将记录窗口

如何使用绑定?

Bind可以帮助克服使用此关键字时遇到的困难,方法是在此处指定一个固定的对象。例如:

var name='globalName';常量对象={name:'myName',sayName:function(){console.log(this.name);}}常量say=obj.sayName;//我们只是存储函数,它的值不会被神奇地传递say();//现在,由于此函数在全局范围内执行,因此将引用全局变量const-boundSay=obj.sayName.bind(obj);//现在,this的值被绑定到obj对象bounday();//现在,这将引用obj对象中的名称:“myName”

一旦函数被绑定到特定的这个值,我们就可以传递它,甚至可以将它放到其他对象的财产中。其价值将保持不变。

bind()方法创建一个新函数,当调用该函数时,将其this关键字设置为所提供的值,并在调用新函数时提供的任何参数之前设置一个给定的参数序列。

第一部分的示例

使用St8从反应包中抓取

import { useState } from "react"

function st8() {
    switch(arguments.length) {
        case 0: return this[0]
        case 1: return void this[1](arguments[0])
        default: throw new Error("Expected 0 or 1 arguments")
    }
}


function useSt8(initial) {
    // this in st8 will be something like [state, setSatate]
    return st8.bind(useState(initial))
}

// usage
function Counter() {
  const count = useSt8(0);
  return (
    <>
      Count: {count()}
      <button onClick={() => count(0)}>Reset</button>
      <button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
    </>
  );
}

第二部分的示例

const add = (a, b) => a+b

someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5) 
add5(10) // 15

// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10) 
add10(5) // 15

我将从理论上和实践上解释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;

我没有读过上面的代码,但我学到了一些简单的东西,所以我想在这里分享一下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函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。

setInterval(this.animate_to.bind(this), 1000/this.difference);