Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7739

What is the purpose of using new operator in this example?

Why would you use the new operator in succession like in the example below.

var x = 0;
function foo() {
    x++;
    this.x = x;
    return foo;
}
var bar = new new foo;
console.log(bar.x); //undefined

UPDATE Actually I didn't notice at first, but when you do:

var bar = new new foo; //you'll get `undefined` `undefined` returned

As opposed to:

var bar = new foo; //you'll get `undefined` returned

UPDATE As Bergi correctly pointed out you'll only get one undefined..Sorry I must not have had enough coffee :)

Upvotes: 2

Views: 60

Answers (1)

Bergi
Bergi

Reputation: 664454

What is the purpose of using new operator in this example?

To baffle you. A lot.

Why would you use the new operator in succession?

You would never, unless you would want to demonstrate that weird code can still work. Although it needs a higher-order function (which returns another function) instead of a normal constructor for that.

OK, let's make it less weird:

var x = new   new Function("this.foo = 'bar';") ();
//          ^ notice the invisible parenthesis ^
x.foo; // bar

Upvotes: 2

Related Questions