-1

what difference is there between the following two ways of creating an object in JavaScript

function createFoo(){
    var _foo = { id: 1 };
    return _foo;
}
var foo = createFoo();

and

function Foo(){
    this.id = 1;
}
var foo2 = new Foo();
NoodleFolk
  • 1,701
  • 1
  • 12
  • 23
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new – thgaskell Nov 22 '14 at 00:41
  • possible duplicate of [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – Mathletics Nov 22 '14 at 00:51

2 Answers2

1

Running the code in the chrome console give us more information about the content of the 2 variables:

> foo
Object {id: 1}
> foo2
Foo {id: 1}

So there is a difference. Spoiler Alert !! The answer lies in the prototype chain:

> foo.__proto__
Object {}
> foo2.__proto__
Foo {}

If you need more details, refer to this great post: https://stackoverflow.com/a/3658673/2523414

Community
  • 1
  • 1
Clément Prévost
  • 5,840
  • 1
  • 27
  • 48
0

There are many differents in the way of instantiating objects that are created and accessed from these functions. For example:

function createFoo(){
   var _foo = { id: 1 };
   return _foo;
}
var foo = createFoo();

If you want to get value of id property, you have to iterate over properties in foo object, like this:

for(var prop in foo){
   //if you want to set new value then
   foo[prop] = 5;
   //then getting value is like this
   console.log(foo[prop]);
}

In your second example it is different in way of getting/setting value:

function Foo(){
    this.id = 1;
} 
var foo2 = new Foo();
foo2.id = 2;//set new value
console.log(foo2.id);

That is all I can think of.

coder
  • 568
  • 3
  • 10
  • 30