This is a little bit of a noob question, but coming from a server side (PHP) background, I am struggling a little with the conceptual differences between the different ways of creating javaScript objects and classes.
I have two snippets, which represent the same code, but implemented in different ways.
What I want to know if when and why would you choose one over the other?
var foo = {
init: function() {
console.log('loading...');
console.log(this.param);
return this;
},
param: '5',
bar: function(){
console.log('bar bar');
this.black();
this.sheep();
return this;
},
black: function(){
console.log('black');
return this;
},
sheep: function(){
console.log('sheep');
console.log(this.param);
return this;
}
};
foo.init().bar();
Then there is option two:
var foo = function(){
return {
init: function() {
console.log('loading...');
console.log(this.param);
return this;
},
param: '5',
bar: function(){
console.log('bar bar');
this.black();
this.sheep();
return this;
},
black: function(){
console.log('black');
return this;
},
sheep: function(){
console.log('sheep');
console.log(this.param);
return this;
}
};
}
foo().init().bar();
Why would you use the return {} in the second example?