Alon
Alon

Reputation: 3906

javascript init an object without the new keyword

What's the difference between:

function Foo(){} var foo1 = Foo();

and

var foo2 = new Foo()

As far as I tested, foo1 gives nothing. typeof foo1 is undefined while with new it's ok as expected.

What's the reason the that without the new keyword I get the undefined result?

Upvotes: 1

Views: 1865

Answers (4)

The code contained a safeguard to bail if the new keyword wasn't used. Which is a good idea because if the new keyword is omitted, the context will be a window.

function MyConstructor(){
  console.log(this.toString());
}

var instance1 = MyConstructor();
var instance2 = new MyConstructor();

This outputs:

"[object Window]"
"[object Object]"

So, in your example it shows undefined as a window which is bind automatically has no foo1 method, in the second case, new instantiate/declare an object has method foo2

Upvotes: 0

plalx
plalx

Reputation: 43718

Here's what's basically happening when you are using new, it:

  1. Creates a new object, let it be o.
  2. Sets the prototype link of o to [constructor].prototype.
  3. Executes the [constructor] with o as the context object (this).
  4. Returns o unless the [consructor] returns a non-primitive value. In that case, that non-primitive value is returned instead of o. (Added these precisions as suggested by @Esailija).

When you are not using new, nothing of this happens and the context object is window, unless the function was invoked on another object. In this case, the context object would be that object.

E.g.

function A() {}
A(); //this points to window

var o = { A: A };

o.A(); //this points to o

Every function can be a constructor in JavaScript, however you must use the new keyword in order to get the expected result.

To avoid mistakes, some people will design their function so that forgetting the new keyword will not be harmful, like below, however there are better alternatives to detect these mistakes, like using code analysis tools like JSHint.

E.g.

function Foo(args) {
    if (!(this instanceof Foo)) {
        return new Foo(args);
    }
    //initialization code
}

Upvotes: 2

Björn Roberg
Björn Roberg

Reputation: 2366

This is because function Foo(){} returns undefined implicitly, i.e. if a function does not have an explicit return statement, the compiler/VM will implicitly add it. However, when you use the new keyword, you instantiate an object from the constructor function.

See this answer for an exact explanation for what the new keyword does.

Upvotes: 4

Neeraj Kumar Gupta
Neeraj Kumar Gupta

Reputation: 2363

Try this

function Foo(){} var foo1 = Foo();

instead of

function Foo(){} var foo1 = foo();

JavaScript is case sensitive language

Upvotes: -2

Related Questions