1
function foo() {
    return {a:9};
}

var bar = foo();
bar.a //returns 9

or

function foo() {
    return {a:9};
}

var bar = new foo(); 
bar.a // returns 9

As far as I know new isnt used with the object literal notation, but how come new does work with it? Also, why is it that prototype can be accessed with new object, but not with the object literal notation?

edit:

I understand it now, if anyone else who stumbles upon this problem/question this might help you understand it:

function foo() {
    this.a = "LOL";
    return "WTF";
};
var bar = new foo(); // bar = [Object object]
var c = foo(); // c = "WTF"
window.a // "LOL"

Also read the accepted answer.

user1534664
  • 3,258
  • 8
  • 40
  • 66
  • Here's a good link: http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful – paulsm4 Dec 06 '12 at 19:32

3 Answers3

7

Using new in this circumstance has nothing to do with what you return, but what this is inside of foo(). Using new, this will be a reference to a foo instance inside of foo() . Without new, this will be the global (probably window)

Brian Cray
  • 1,277
  • 1
  • 7
  • 19
5

It works because if you explicitly return a non-primitive type from a function that is being called as a constructor (using new), then that object is returned instead of the created object. You are not using the created object in your function in any way, so new is redundant.

Here you can see that it doesn't work with primitives:

function test() {
    return "string"; //This is not returned when called with new, because it's primitive
}

var a = new test();
a == "string" // false

function test() {
    return new String("string"); //This is returned when called with new, because it's an object, like {}
}

var b = new test();
b == "string" //true

I am using == and new String for demonstration purposes. You should never use new String in practice.

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

{} is just a short cut for new Object()

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • 2
    Sort of, but there is technically a difference. – Brad Dec 06 '12 at 19:27
  • I hate to mark someone down ... but that's just not accurate. Sorry :( See Brian Cray's and Esailja's responses. – paulsm4 Dec 06 '12 at 19:29
  • Like what? `({}).constructor === Object` – Yury Tarabanko Dec 06 '12 at 19:32
  • `{}` works even if `Object` is set to `null`. `Object = null; new Object(); TypeError: object is not a function` `var a = {}; a.constructor === Object; //false` – Esailija Dec 06 '12 at 19:35
  • http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf page 65 The production ObjectLiteral : { } is evaluated as follows: 1. Return a new object created as if by the expression new Object() where Object is the standard builtin constructor with that name – Yury Tarabanko Dec 06 '12 at 19:41
  • Yes, but in practice that easily leads to a security flaw that gmail once had. – Esailija Dec 06 '12 at 19:41