function Person(name) {
this.name = name;
return this;
}this can be used as a
- constructor function
- regular function
the only difference in using them is by using
newkeyword
- it always returns this even if not explicitly mentioned
- if return anything non object, it is ignored
function Person(name) {
this.name = name;
return name;
}
let john = new Person("John")
// john is Object { name: "John" }- any non object won't be returned
true, "23", "anything", 53, 3.14won't be returned- it will always return
this
function Person(name) {
this.name = name;
return {};
}
let john = new Person("John")
// john is {}john.namewon't work and would be undefined
function Person(name) {
this.name = name;
return () => {};
}
let john = new Person("John")
// john is () => {}john.namewon't return"John"- instead
""would be returned, becausejohn.namewould be equivalent of callingFunction.name - in this case function does not have a name hence emptry string is returned
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
return this;
}this function returns this
using it as a constructor
let newCar = new Car("Fiat", "Distro", 1998)newCaris the same as this( in context of Car)newvariable does following- creates a blank object with a blank
this - looks at what properties the
Carfunction has - assigns all what
Carproperties to the newly and blank object and its this - this newly created and then newly assigned this is assigned to
newCarvariable - in other words
newCarinherits from the prototype ofCar newCar's parent prototype would beCar
- creates a blank object with a blank
using it as a function
let newCar = Car("Fiat", "Distro", 1998)- what happens is
Caris run as a normal function - whenever we run a normal function (not arrow)
thisrefers to whatever called the function - if we console
newCarwe will get theglobalorwindowobject - that object would now have values of
model,make&year gobal.modeletc would work
const Car = (make, model, year) => {
this.make = make;
this.model = model;
this.year = year;
return this;
}- in this scenario
let newCar = Car("Fiat", "Distro", 1998)newCarwould be an{ make: 'Fiat', model: 'Distro', year: 1998 }- because every arrow function creates a new
thisobject for every execution - the
thisin arrow functions does not refer to its caller'sthis, like regular functions
const Car = (make, model, year) => {
this.make = make;
this.model = model;
this.year = year;
}
let newCar = Car("Fiat", "Distro", 1998)newCarhere would beundefinedbecause the context of this is immediately lost and is not passed to newCar- it could be passed using
let newCar = new Car("Fiat", "Distro", 1998)- because
newalways creates a new object and copies the entire prototype of the Object and assign's it to the variable - and it by default always returns
thisunless another object type is explicitly returned