Preejith P
Preejith P

Reputation: 39

Why does constructor function (with "return this") return window object?

I have a function

function Person(name){
this.name = name;
return this;
}
alert(Person("somename"));

This is returning [Object Window], how we can change this to [object object]? Is there any way we can change this function to get [object object] without changing signature.

Upvotes: 0

Views: 160

Answers (1)

jfriend00
jfriend00

Reputation: 707278

In Javascript, when you call a function as in:

Person("somename")

The this pointer in that function call is set to either the global object or undefined (if running in strict mode). That's what is happening in your statement:

alert(Person("somename"));

If, you want Person() to work as a constructor where a new Person object is created for you automatically, then you must include the new operator as in:

alert(new Person("somename"));

The new operator then creates a new object of that type and then calls the constructor with the this pointer set to that new object. That is exactly what it is for. Also, there is no need to do return this when using a constructor with new as that is done for you automatically.


You could make the form work you were using without using new, but then you'd have to create your own object in the Person function like this:

function Person(name){
    var p = {};      // create an empty object
    p.name = name;   // assign the name field
    return p;        // return the newly created object
}

There are some drawbacks to doing it this way, particularly in that instanceof Person won't work properly, so using the new operator is generally preferred. I find that using new also makes the code more readable because it's more obvious when you are creating a new object and when you are just calling a function.

Upvotes: 1

Related Questions