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
new
keyword
- 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.14
won't be returned- it will always return
this
function Person(name) {
this.name = name;
return {};
}
let john = new Person("John")
// john is {}
john.name
won't work and would be undefined
function Person(name) {
this.name = name;
return () => {};
}
let john = new Person("John")
// john is () => {}
john.name
won't return"John"
- instead
""
would be returned, becausejohn.name
would 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)
newCar
is the same as this( in context of Car)new
variable does following- creates a blank object with a blank
this
- looks at what properties the
Car
function has - assigns all what
Car
properties to the newly and blank object and its this - this newly created and then newly assigned this is assigned to
newCar
variable - in other words
newCar
inherits 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
Car
is run as a normal function - whenever we run a normal function (not arrow)
this
refers to whatever called the function - if we console
newCar
we will get theglobal
orwindow
object - that object would now have values of
model
,make
&year
gobal.model
etc 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)
newCar
would be an{ make: 'Fiat', model: 'Distro', year: 1998 }
- because every arrow function creates a new
this
object for every execution - the
this
in 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)
newCar
here would beundefined
because 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
new
always 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
this
unless another object type is explicitly returned