-1

in this question, I don't want to ask "Function", i want to ask "function" puzzle

<script type="text/javascript">
    var test = function() {
        alert('a');
    };

    var test1 = new function() {
        alert('b');
    };
</script>

why it will pop up the "b"?

clevertension
  • 6,929
  • 3
  • 28
  • 33
  • See http://stackoverflow.com/questions/2274695/new-function-with-lower-case-f-in-javascript – Ayush Feb 28 '13 at 06:14

5 Answers5

1

Function (p1, p2, … , pn, body)

When the Function function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “p” arguments, and where body might also not be provided), the following steps are taken:

Create and return a new Function object as if the standard built-in constructor Function was used in a new expression with the same arguments.

check :Is JavaScript's "new" keyword considered harmful?

Community
  • 1
  • 1
Amrendra
  • 2,019
  • 2
  • 18
  • 36
0

new function will execute the function, you can use an IIFE (Immediately- Invoked Function Expression) as well:

var test1 = (function() {
  alert('b');
}());
ColinE
  • 68,894
  • 15
  • 164
  • 232
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

new is used for the Factory pattern in Javascript. It creates and returns an object by executing a constructor function. In your case it doesn't make sense to use new.

Greg
  • 3,370
  • 3
  • 18
  • 20
0

Functions which are built to be used as constructors don't require parens, if you aren't passing any arguments:

var Person = function () { this.is_alive = true; },
    bob = new Person;

bob.is_alive;

...but any function can be called as a constructor, whether you're using the returned object or not...

new function () { console.log("Bob"); }

this won't save the function anywhere -- it will run it, in place, instantly.

Norguard
  • 26,167
  • 5
  • 41
  • 49
0

See What is the 'new' keyword in JavaScript? for a basic description of the new keyword.

Essentially, you are calling the constructor to a new object. Let me show you.

var Animal = function(name) {
    alert("Animal Created: " + name);
}

jaguar = new Animal("Cool");

The only difference from that and what you did was declare the function in the same line as defining the new object:

jaguar = new function(name) {
    alert("Animal Created: " + name);
}

That's why the "b" was printed out.

Community
  • 1
  • 1
yourdeveloperfriend
  • 1,600
  • 1
  • 9
  • 19