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
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 messyvar that=this;assignments.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.