Function Syntax
function normalFunction() {
}
const arrowFunction = () => {
}
This Reference
const person = {
name: 'Jeet',
getName() {
console.log(this); //{ name: 'Jeet', getName: [Function: getName] }
console.log(this.name); // Jeet
}
}
person.getName();
Here because of normal function, the method attached with the object picks up this as the person object. However, if there is another normal function then it will not pick up this as the person object but rather global object
const person = {
name: 'Jeet',
getName() {
console.log(this);//{ name: 'Jeet', getName: [Function: getName] }
console.log(this.name); // Jeet
function getUserName() {
console.log(this); //global object
console.log("this.name",this.name) // undefined
}
getUserName();
}
}
person.getName();
Now in order to bind the this to the person object instead of the global object we can use the call method
const person = {
name: 'Jeet',
getName() {
console.log(this); //{ name: 'Jeet', getName: [Function: getName] }
console.log(this.name);
function getUserName() {
console.log(this); //{ name: 'Jeet', getName: [Function: getName] }
console.log("this.name",this.name)
}
getUserName.call(this);
}
}
person.getName();
Arrow function always refers to the lexical this. This scope problem is solved by arrow function. The arrow function always looks up the scope for a regular function and will take it’s scope. If the arrow function is at the global level, it will take the this scope as the global object.
const person = {
name: 'Jeet',
getName() {
console.log(this);
console.log(this.name);
const getUserName = () => {
console.log(this);
console.log("this.name",this.name)
}
getUserName();
}
}
person.getName();
Arrow functions cannot be used as constructor function. Only function declaration can be used as constructor function. Function expression cannot be used as constructor function. Arrow function are also function expression as it needs a variable to create.
function Person(name, age) {
this.name = name;
this.age = age;
}
const p1 = new Person("jeet", 29);
Regular functions are hoisted. But arrow functions are not hoisted;
normal(); // normal
arrow(); //error
function normal() {
console.log('normal');
}
const arrow = () => {
console.log('arrow');
}
Regular functions have arguments object passed to it. But arrow function does not have arguments object. Instead we have to use the spread operator
function normal() {
console.log('arguments', arguments);
}
const arrow = (...args) => {
console.log('arguents', args);
}
normal(2,"add"); // arguments [Arguments] { '0': 2, '1': 'add' }
arrow(2, "add"); //arguents [ 2, 'add' ]