6

Possible Duplicate:
What is the 'new' keyword in JavaScript?
creating objects from JS closure: should i use the “new” keyword?

See this code:

function friend(name) {
    return { name: name };
}

var f1 = friend('aa');
var f2 = new friend('aa');

alert(f1.name); // -> 'aa'
alert(f2.name); // -> 'aa'

What's the difference between f1 and f2? ​

Community
  • 1
  • 1
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    One has the word "new" in front of it :-) One is just a regular function, and the other is a new instance of something, usually an object, and just about everything is an object in JS. – adeneo Mar 31 '12 at 02:34
  • I think this is very much eloquent question in compare to the other duplicate. – Amit Shah Nov 16 '17 at 03:52

1 Answers1

4

The new in your case isn't usefull. You only need to use the new keyword when the function uses the 'this' keyword.

function f(){
    this.a;
}
// new is required.
var x = new f();

function f(){
    return {
        a:1
    }
}
// new is not required.
var y = f();
Larry Battle
  • 9,008
  • 4
  • 41
  • 55