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


当前回答

考虑下面列出的简单程序,

//we create object user
let User = { name: 'Justin' };

//a Hello Function is created to Alert the object User 
function Hello() {
  alert(this.name);
}

//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();

//we create an instance to refer the this keyword (this.name);

其他回答

/**
 * Bind is a method inherited from Function.prototype same like call and apply
 * It basically helps to bind a function to an object's context during initialisation 
 * 
 * */

window.myname = "Jineesh";  
var foo = function(){ 
  return this.myname;
};

//IE < 8 has issues with this, supported in ecmascript 5
var obj = { 
    myname : "John", 
    fn:foo.bind(window)// binds to window object
}; 
console.log( obj.fn() ); // Returns Jineesh

bind函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。

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

bind是一个在java脚本原型中可用的函数,因为名称建议bind用于将您的函数调用绑定到上下文,无论您正在处理什么,例如:

var rateOfInterest='4%';var轴库={利率:“10%”,getRateOfInterest:函数(){return this.rateOfInterest;}}axisBank.getRateOfInterest()//“10%”让我们知道AxisBankInterest=axsBank.getRateOfInterest//当您想将函数调用分配给变量时,我们使用此语法knowAxisBankInterest();//默认情况下,您将在此处获得“4%”的输出,该函数称为wrt全局上下文let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank)//因此这里我们需要将函数调用绑定到其本地上下文knowExactAxisBankInterest()//“10%”

简单的例子

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()的最简单用法是生成一个函数,无论它是如何被调用的。

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()