-2

I created a class using function like -

function Person(name) {
  this.name = name;
}

var obj = new Person("Ferdinand");

console.log(obj.name);

I am creating an object obj and prints its property name it is working fine and prints "Ferdinand", but if we forget to write new key word like below program -

function Person(name) {
  this.name = name;
}

var obj = Person("Ferdinand");

console.log(name);

Here I am not able to understand why name is available in console, it is printing "Ferdinand". But we are using Person as a function and assigning name variable in function itself so why its value is available outside function.

cweiske
  • 27,869
  • 13
  • 115
  • 180
Sushil Kumar
  • 149
  • 7
  • 3
    Because without `new` the `this` keyword refers to the `window` object and `window.name = name` sets a global variable. – JJJ Apr 08 '17 at 10:34
  • 3
    Possible duplicate of [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript), specifically [this answer](http://stackoverflow.com/a/1646957/502381) – JJJ Apr 08 '17 at 10:35

1 Answers1

2

JavaScript does not implement objects in the classical sense. Instead, they are implemented directly:

var thing={};   //  new object

Because you typically want multiple objects to follow a common pattern and behaviour, you can use what is called a constructor function to help. In your example, Person is a constructor function.

When using a constructor, you call it indirectly using the new command:

var thing = new Person(…);

In fact, there’s a lot of magic going on here:

  • JavaScript begins by creating a new object: var thing={};.
  • Then the this key word is assigned to the new object
  • Finally the constructor is run, using the this value to assign local values.

If you call a constructor function directly, the first 2 steps do not apply, and the function is left trying to work in its own definition of this which is generally not what you want.

If you really want to call the constructor function without bothering with new, you can try the following:

function Person(data) {
    //  “new” safe constructor
    if(!(this instanceof Person)) {
    return new Person(data);
}

This new version checks whether it is being called as a proper constructor, and, if not, calls itself properly.

Manngo
  • 8,349
  • 6
  • 50
  • 74