Javascript's this
Simple function invocation
Consider the following function:
function foo() {
console.log("bar");
console.log(this);
}
foo(); // calling the function
Note that we are running this in the normal mode, i.e. strict mode is not used.
When running in a browser, the value of this would be logged as window. This is because window is the global variable in a web browser's scope.
If you run this same piece of code in an environment like node.js, this would refer to the global variable in your app.
Now if we run this in strict mode by adding the statement "use strict"; to the beginning of the function declaration, this would no longer refer to the global variable in either of the environments. This is done to avoid confusions in strict mode. this would, in this case just log undefined, because that is what it is, it is not defined.
In the following cases, we would see how to manipulate the value of this.
Calling a function on an object
There are different ways to do this. If you have called native methods in Javascript like forEach and slice, you should already know that the this variable in that case refers to the Object on which you called that function (Note that in javascript, just about everything is an Object, including Arrays and Functions). Take the following code for example.
var myObj = {key: "Obj"};
myObj.logThis = function () {
// I am a method
console.log(this);
}
myObj.logThis(); // myObj is logged
If an Object contains a property which holds a Function, the property is called a method. This method, when called, will always have it's this variable set to the Object it is associated with. This is true for both strict and non-strict modes.
Note that if a method is stored (or rather, copied) in another variable, the reference to this is no longer preserved in the new variable. For example:
// continuing with the previous code snippet
var myVar = myObj.logThis;
myVar();
// logs either of window/global/undefined based on mode of operation
Considering a more commonly practical scenario:
var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself
The new keyword
Consider a constructor function in Javascript:
function Person (name) {
this.name = name;
this.sayHello = function () {
console.log ("Hello", this);
}
}
var awal = new Person("Awal");
awal.sayHello();
// In `awal.sayHello`, `this` contains the reference to the variable `awal`
How does this work? Well, let's see what happens when we use the new keyword.
- Calling the function with the
new keyword would immediately initialize an Object of type Person.
- The constructor of this
Object has its constructor set to Person. Also, note that typeof awal would return Object only.
- This new
Object would be assigned the prototype of Person.prototype. This means that any method or property in the Person prototype would be available to all instances of Person, including awal.
- The function
Person itself is now invoked; this being a reference to the newly constructed object awal.
Pretty straightforward, eh?
Note that the official ECMAScript spec nowhere states that such types of functions are actual constructor functions. They are just normal functions, and new can be used on any function. It's just that we use them as such, and so we call them as such only.
Calling functions on Functions: call and apply
So yeah, since functions are also Objects (and in-fact first class variables in Javascript), even functions have methods which are... well, functions themselves.
All functions inherit from the global Function, and two of its many methods are call and apply, and both can be used to manipulate the value of this in the function on which they are called.
function foo () { console.log (this, arguments); }
var thisArg = {myObj: "is cool"};
foo.call(thisArg, 1, 2, 3);
This is a typical example of using call. It basically takes the first parameter and sets this in the function foo as a reference to thisArg. All other parameters passed to call is passed to the function foo as arguments.
So the above code will log {myObj: "is cool"}, [1, 2, 3] in the console. Pretty nice way to change the value of this in any function.
apply is almost the same as call accept that it takes only two parameters: thisArg and an array which contains the arguments to be passed to the function. So the above call call can be translated to apply like this:
foo.apply(thisArg, [1,2,3])
Note that call and apply can override the value of this set by dot method invocation we discussed in the second bullet.
Simple enough :)
Presenting.... bind!
bind is a brother of call and apply. It is also a method inherited by all functions from the global Function constructor in Javascript. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function with the thisArg and arguments pre-set. Let's take an example to better understand this:
function foo (a, b) {
console.log (this, arguments);
}
var thisArg = {myObj: "even more cool now"};
var bound = foo.bind(thisArg, 1, 2);
console.log (typeof bound); // logs `function`
console.log (bound);
/* logs `function () { native code }` */
bound(); // calling the function returned by `.bind`
// logs `{myObj: "even more cool now"}, [1, 2]`
See the difference between the three? It is subtle, but they are used differently. Like call and apply, bind will also over-ride the value of this set by dot-method invocation.
Also note that neither of these three functions do any change to the original function. call and apply would return the value from freshly constructed functions while bind will return the freshly constructed function itself, ready to be called.
Extra stuff, copy this
Sometimes, you don't like the fact that this changes with scope, especially nested scope. Take a look at the following example.
var myObj = {
hello: function () {
return "world"
},
myMethod: function () {
// copy this, variable names are case-sensitive
var that = this;
// callbacks ftw \o/
foo.bar("args", function () {
// I want to call `hello` here
this.hello(); // error
// but `this` references to `foo` damn!
// oh wait we have a backup \o/
that.hello(); // "world"
});
}
};
In the above code, we see that the value of this changed with the nested scope, but we wanted the value of this from the original scope. So we 'copied' this to that and used the copy instead of this. Clever, eh?
Index:
- What is held in
this by default?
- What if we call the function as a method with Object-dot notation?
- What if we use the
new keyword?
- How do we manipulate
this with call and apply?
- Using
bind.
- Copying
this to solve nested-scope issues.
thispeter.michaux.ca/articles/javascript-widgets-without-this – Marcel Korpel Jun 27 '10 at 14:53thiskeyword: rainsoft.io/gentle-explanation-of-this-in-javascript – Dmitri Pavlutin May 24 '16 at 7:20