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();
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();
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
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.