How to: apply(), bind()

Here is the my struggling part of understanding parts in JS.

At first glance, it seemed so peculiar to me.

So before going into these method in detail, I’m gonna talk about what “this” means in JS.

“this”(I call it with “” around this to clarify) value is depended on the context where we use “this”.

For example,

// inside global scope in browser
this === window
// inside global scope in node.js
this === global

The two line about return true, but in strict mode, the behavior changed a bit.

'use strict';
function example() {
return this;
}
example()// ->undefined;

In strict mode, this refers to its own scope this value.

And there might be time when you wanna “this” value from one context to another.

That’s the point that we would use call, or apply.

Let’s see the code to see how it works:

let obj = {
  one: "just for the test",
  two: function(a) { return a }
}
function func() {
  return this.two("two has been invoked") + " " + this.one;
};
console.log(func.apply(obj)); // "two has been invoked just for the test"

First, I declare the obj that I’m gonna use as “this” value of func.

Func will be invoked upon the obj variable, which means func can refer the specific obj. It’s because we call func on a last line, like:

func.apply(obj)// func is called with obj

Besides, apply takes second parameter, which is applied to the argument of func function.

Call works in a similar way to apply, but I’d prefer to use apply function since it takes second parameter as array-like, which means we don’t take care how many arguments func is gonna take.

Later, I will write about the bind function.

The official documentation could be seen in MDN, by the way.