What is `this`?
A brief look into the `this` keyword in javascript
Working on Nodejs at work recently made me remember how confusing javascript can be. There are a lot of quirks that make it a powerful language, but for developers coming from a more strict OOP background they can seem broken. In this post I’m going to talk about this
in javascript.
New binding
If the function is called with the new keyword, this
is the newly constructed object.
function Foo(bar) {
this.bar = bar;
console.log(this);
}
new Foo('foobar'); // Foo { bar: 'foobar' }
Explicit binding
If the function is called with call
or apply
then this
is the explicitly specified object, even inside a hard binding (more on this below)!
const foo = function() {
console.log(this.x);
}
const bar = {
x: 'foobar'
}
foo.call(bar); // foo
Hard binding
Hard bindings are when there has been an explicit bind within a funtion. This means that even if said function is called explicitly, this
will not change in the final call.
const foo = function() {
console.log(this.x);
}
const bar = {
x: 'foobar'
}
const baz = {
x: 'foobarbaz'
}
function doFoo() {
foo.call(bar);
}
doFoo(); // foobar
doFoo.call(baz); // foobar
Implicit binding
If the function is called with a context, e.g. the thing containing the object is this
.
function foo() {
console.log( this.a );
}
function doFoo(fn) {
// `fn` is just another reference to `foo`
fn();
}
var obj = {
a: 2,
foo: foo
};
var a = "global";
doFoo(obj.foo); // global
Default binding
The default binding is the global object. but if in strict mode this
is undefined.
function foo() {
console.log(this.a);
}
var a = 2;
foo(); // 2
But if strict
mode is active, then this
is undefined.
function foo() {
"use strict";
console.log(this.a);
}
var a = 2;
foo(); // TypeError: `this` is `undefined`
But remember… strict
mode has to be in scope too!
function foo() {
console.log(this.a);
}
var a = 2;
(function(){
"use strict";
foo(); // 2
})();
Wow… That’s a lot to remember
Having to keep track of this
and it’s different meanings have been quite daunting to me but I hope this small post has cleared some things up for you and you can see how these different scopes of this
can be useful to you in different circumstances.
It’s important to remember that javascript is a functional language with object orientated aspects to it, so you should design your function and objects around what they do instead of what they are.