this keyword in javascript

The purpose of this keyword allows us to reuse functions with different context by allowing us to decide which object should be referenced when invoking a function or method.

Implicit Binding

var me = {
  name: "Tom",
  age: 25,
  sayName: function(){
    console.log(this.name);
  }
}

me.sayName();

When you invoke a method look to the left of the dot for meaning of this.

Explicit Binding

.call()

used to explicitly define the context that the this keyword will reference, you can also pass parameters to the function you are chaining this method onto.

.apply()

the same as call, except rather than passing multiple parameters after explicitly defining the reference to be used by the this keyword, you can pass an entire array.

.bind()

almost the same as call, but now it will return a new function instead of invoking the function you are chaining this method onto.

new Binding The new keyword is used to create a new object and defining this is bound to the new object being constructed.

var Animal = function(color, name, type){
	this.color = color;
    this.name = name;
    this.type = type;
}
var zebra = new Animal(‘black and white’, ‘Zorro’, ‘Zebra’);

window Binding

If the this keyword is not bound to an object e.g. called globally. It will default to referencing the window object.

Posted Oct 23, 2017, 2:12 AM UTC · edited

306
bgdam•

Great explanation. However, with ES6+ becoming the new norm, please edit this to also include the effect of the fat arrow on this. This would be especially useful since it lets people avoid a lot of messy var that=this; assignments.

5
folkrav•

Especially considering the most popular modern browsers are now support ES6 natively. For production code, I wouldn't go the native way without transpiling yet for backward compatibility reasons, but still. It's the future of the language.

1
jillesme•

Cool sub! Am I the only one who is slightly bothered by the misspelling of JavaScript?

4
cyphrrrOP•

hopefully

15
mikeyjk•

I doubt it, attention to detail is important and getting triggered by small deviations is probably pretty common for developers. I prefer lowercase characters due to avoiding the extra shift key press (on phone right now).

op: Anyway cool post and cheers for creating this sub!

6
NoNameWalrus•

What is the usage of each?

Like, 1) syntax 2) why would I want to bind a different context of this?

1
Balduracuir•

There is a post on another subreddit where people asked for explanation. It could complete this post :)

1