DEV Community

Cover image for Javascript Object #5
Asir-Sam
Asir-Sam

Posted on

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');`
Enter fullscreen mode Exit fullscreen mode

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

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

`console.log(person.firstName);

TypeError: Cannot read property 'firstName' of undefined
`
Enter fullscreen mode Exit fullscreen mode

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

`person.getFullName();
Code language: CSS (css)

Error:

TypeError: Cannot read property 'getFullName' of undefined`
Enter fullscreen mode Exit fullscreen mode

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;
`
Enter fullscreen mode Exit fullscreen mode

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);`
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)