var myButton = {content: 'OK',click() {console.log(this.content + ' clicked');}};
myButton.click();
var looseClick = myButton.click;looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);boundClick(); // bound, 'this' is myButton
var myButton = {... // As abovehookEvent(element) {// Use bind() to ensure 'this' is the 'this' inside click()element.addEventListener('click', this.click.bind(this));}};
或:
var myButton = {... // As abovehookEvent(element) {// Use a new variable for 'this' since 'this' inside the function// will not be the 'this' inside hookEvent()var me = this;element.addEventListener('click', function() { me.click() });}};
或:
var myButton = {... // As abovehookEvent(element) {// => functions do not change 'this', so you can use it directlyelement.addEventListener('click', () => this.click());}};
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 modulevar boundGetX = getX.bind(module);boundGetX(); // 81
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 rangevar result = boundedFunc(15); //passing valueconsole.log(result) // will give true;
/*** 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 5var obj = {myname : "John",fn:foo.bind(window)// binds to window object};console.log( obj.fn() ); // Returns Jineesh
function Multiplier(factor) {this.factor = factor;}
Multiplier.prototype.multiply = function(x) {return this.factor * x;}
function ApplyFunction(func, value) {return func(value);}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50console.log(ApplyFunction(mul.multiply.bind(mul), 10));
实现有状态的CallBack
下面的示例显示了使用this的绑定如何使对象方法充当可以轻松更新对象状态的回调。
function ButtonPressedLogger(){this.count = 0;this.onPressed = function() {this.count++;console.log("pressed a button " + this.count + " times");}for (let d of document.getElementsByTagName("button"))d.onclick = this.onPressed.bind(this);}
new ButtonPressedLogger();
var x = 9; // this refers to global "window" object here in the browservar person = {x: 81,getX: function() {return this.x;}};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();document.getElementById("demo2").innerHTML = x2();
var rateOfInterest='4%';var axisBank={rateOfInterest:'10%',getRateOfInterest:function(){return this.rateOfInterest;}}axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntaxknowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'
let obj = {prop1: 1,func: function () { console.log(this); }}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,// customFunc() is shorthand for window.customFunc()// Therefore window will be logged
bind是如何使用的?
Bind可以帮助克服this关键字的困难,因为它有一个固定的对象,this将引用它。例如:
var name = 'globalName';
const obj = {name: 'myName',sayName: function () { console.log(this.name);}}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
var name = "sample";function sample(){console.log(this.name);}var cb = sample.bind(this);
function somefunction(cb){//other codecb();}somefunction.call({}, cb);
//we create object userlet User = { name: 'Justin' };
//a Hello Function is created to Alert the object Userfunction Hello() {alert(this.name);}
//since there the value of this is lost we need to bind user to use this keywordlet user = Hello.bind(User);user();
//we create an instance to refer the this keyword (this.name);
<pre> note: do not use arrow function it will show error undefined </pre>
let solarSystem = {sun: 'red',moon : 'white',sunmoon : function(){let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';return dayNight;}}
let work = function(work,sleep){console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()console.log('i work in '+ work +' and sleep in '+sleep);}
let outPut = work.bind(solarSystem);outPut('day','night')
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))}
// usagefunction 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 someThisadd5 = 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