Search This Blog

2026/08/09

function call with new keyword

 


function person(fistName, lastName) {
    this.fistName = fistName;
    this.lastName = lastName;
}

var person1 = new person("John", "Doe");
var person2 = person("Jane", "Smith");

console.log(person1); // John Doe
console.log(person2); // undefined

Output:
person { fistName: 'John', lastName: 'Doe' }
undefined

Notes:
    whenever you call a function with the `new` keyword, it creates a new object and sets the
    context 0f `this` to that new object. In the case of `person1`, it correctly creates a
    new instance of the `person` function, and you can see the properties `fistName` and
    `lastName` are set to "John" and "Doe" respectively.

    but when you call `person` without the `new` keyword, as in the case of `person2`,
    it does not create a new object. Instead, it calls the function in the
    global context (or undefined in strict mode), and since there is no return
    statement in the function, it returns `undefined`. Therefore, `person2` is `undefined`,
    and trying to access its properties will result in an error.


No comments:

Post a Comment