Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between `f()` and `new f()`? [duplicate]

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? ​

like image 635
Freewind Avatar asked Mar 31 '12 02:03

Freewind


1 Answers

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();
like image 114
Larry Battle Avatar answered Sep 28 '22 01:09

Larry Battle