Binding
Default Binding
Default binding refers to how this is the global context whenever a function is invoked without any of these other rules. If we aren't using a dot and we aren't using call(), apply(), or bind(), our this will be our global object.
This is all about where a function is invoked.
Implicit Binding
Implicit binding occurs when dot notation is used to invoke a function.
var MyObject = function (){
this.name = 'MyObjectName';
this.myProperty = 'property';
};
MyObject.prototype.doStuff = function (action) {
console.log(this.name + ' is ' + action + '!');
}
var obj = new MyObject();
obj.doStuff('awesome'); // prints 'MyObjectName is awesome!'
In implicit binding, whatever is to the left of the dot becomes the context for this in the function.
Explicit Binding
These methods allow us to borrow functions and set the this value in function invocation.
call(), apply() & bind()
let user = {
firstName: "John"
};
function func() {
alert(this.firstName);
}
let funcUser = func.bind(user);
funcUser(); // John