Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 5, 2023 11:55 am GMT

Javascript Object 5

Very Warm Welcome,
As it was very warm here in mid-afternoon of mid-summer days
In the last Chapter we've created an Object using the Constructor function,as i told we have to call the Constructor Function with "new" keyword.But whatif we call that without the new keyword.let's see about that in this Post.

Technically, you can call a constructor function like a regular function without using the new keyword like this:

`let friends = Name('Joey','Chandler');`

In this case, the Person just executes like a regular function. Therefore, the this inside the Person function doesnt bind to the person variable but the global object.

If you attempt to access the firstName or lastName property, youll get an error:

`console.log(person.firstName);TypeError: Cannot read property 'firstName' of undefined`

Similarly, you cannot access the getFullName() method since its bound to the global object.

`person.getFullName();Code language: CSS (css)Error:TypeError: Cannot read property 'getFullName' of undefined`

Inoder to Prevent this ES6 has introduced new property called new.target.
If the constructor called with the new keyword it would return the reference of the Function.Otherwise it'll return undefined.

Let's see example for the property,

`function Person(firstName, lastName) {    if (!new.target) {        throw Error("Cannot be called without the new keyword");    }    this.firstName = firstName;    this.lastName = lastName;`

From this Block,if You call the Construction function with new keyword it will return the new Object otherwise it'll throw an error.

Alternatively we can also do another way to fix this,

`function Person(firstName, lastName) {    if (!new.target) {        return new Person(firstName, lastName);    }    this.firstName = firstName;    this.lastName = lastName;}let person = Name("Joe", "Phoebhe");console.log(person.firstName);`

Thus it'll return new Object even though we call the Constructor Function without new keyword.

That's for now,we'll meet in future Object Post,Bye..

Thanks for you warm Time,
Sam


Original Link: https://dev.to/samr/javascript-object-5-4nke

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To