1

So I've been trying to learn a bit about JS context and understanding the "this" keyword. This is some code I've been working with:

var addNumbers = function(num1, num2){
  console.log(num1+num2);
}

var newAdd = addNumbers.bind(this,1,2);

newAdd();

The above logs the value 3, as it should. But if I call addNumbers.bind without the "this" keyword:

var newAdd = addNumbers.bind(1,2);

The newAdd() call returns NaN. Why does this NaN happen? and also, I only came across the solution of adding "this" as a first parameter by trying things out and not necessarily out of intuition. Why does passing "this" as a parameter work? and what context does the "this" in this case represent? Thanks.

EDIT: This question is different from any .bind() related questions because It is not asking for a general explanation of this function. I am asking about a specific use case and need a specific answer. Other suggested duplicates were more generalized and were more open to different types of answers.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • @EngineerDollery added an explanation as to why it is not. The answer i'm seeking is more specific and it's about a certain aspect of .bind(), as opposed to a general explanation of .bind() – Giancarlo Manuel Guerra Salvá May 20 '16 at 11:28
  • I'm not willing to remove my close-dupe vote on that basis, sorry. I think the referenced Q answers this query too -- and quite clearly. I think it's a duplicate of more than that question too, but I can only vote for one duplicate. The answers you have all tell you that the first argument is substituted for `this`, that's the same thing you'll learn by reading the linked dupe. – Software Engineer May 20 '16 at 11:34

2 Answers2

3

.bind is used to assign the "this" context to another object

In your case, .bind(1,2) assigned "this" as 1 and the parameters are num1=2, num2=undefined, and 2+undefined is NaN in JS

If you have a function in an object, say obj.func(asd), thiswill be obj in the function func. If you want to change the context of thisyou can use bind or apply (that's like bind, but it calls directly the function, instead of creating a new one)

olivarra1
  • 3,269
  • 3
  • 23
  • 34
0

Simply put, because the Function#bind function always takes the function's this context as the first argument:

fun.bind(thisArg[, arg1[, arg2[, ...]]])

In your example, you are passing 1 as the value of this (which is not invalid, but is probably not what you're trying to do):

var newAdd = addNumbers.bind(1,2);

So if you don't need the this argument, you could just pass null:

var newAdd = addNumbers.bind(null, 1, 2);
nils
  • 25,734
  • 5
  • 70
  • 79