Reputation: 122
I had two arrays for storing function/method. when I did not use bind , I could find the index in the array. but when I used bind , it could not be found.
function print(){}
var functionArray1 = new Array();
functionArray1.push(print);
console.log(functionArray1.indexOf(print));
var functionArray2 = new Array();
functionArray2.push(print.bind(this));
console.log(functionArray2.indexOf(print.bind(this)));
result: 0 -1
Upvotes: 2
Views: 86
Reputation: 1147
when I used bind , it could not be found
Every time you use .bind()
, it returns a new function. Since you called it twice, 2 new functions got created, and one isn't the same as the other (they point to different memory addresses).
function print() {}
const printA = print.bind(this) // this generates a function at a certain memory address
const printB = print.bind(this) // this generates another function at another memory address
console.log("is printA == printB ?", printA == printB) // false
const printC = printA // this declares a new constant that points to an existing address
console.log("is printC == printA ?", printC == printA) // true
Hope this helps clarify. Cheers,
Upvotes: 0
Reputation: 371029
bind
creates a new function. indexOf
will only return zero or a positive index if the passed object exactly matches one of the items in the array - so, for example, for objects, functions, and primitives, they must be ===
for the indexOf
test to pass.
function print() {}
const boundPrint = print.bind(this);
console.log(boundPrint === print);
Otherwise, if the passed object is not ===
to any elements in the array, -1
will be returned by indexOf
. This is expected behavior.
Upvotes: 1