Undestanding this
function foo(){
console.log(this.name);
}
There are four rules to identify what this refers to in a given context
-
Default binding:
- points to the global or window object foo();
-
implicit binding
- points to the object using which the method is innvoked;
The object that is standing before the dot
is what this keyword will be bound to.obj.foo();
-
Explicit binding
- possible to set explicit value by one of these methods obj.foo.apply(person,[]); obj.foo.call(person, ,,,,); foo.call(person,...);
-
Constructor / new Binding
- value is set the newly created/instantiated Object new Constructor();
And there is a priority, whic is 4 3 2 1
The above 4 rules apply inside a normal function, but not in arrow functions
Special case
Arrow functions
- In case of an arrow function, 2,3,4 will not work.
- Inside arrow function the value points to value of this which is in enclosing block where the method is invoked and not where its defined.``
Top comments (0)