Reputation: 675
I'm new to JS and studied some code from web apps. Can anybody tell me the difference between these two declarations, are they both kind of objects with featured functions? When use which declaration?
a) a self evoking function:
namespace.myCanvas= (function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var foo = function(...){...}
return {
canvas: canvas,
context: context,
foo: foo
}
})();
b) a function that can give out information about an object, I guess:
function makeRectangle(xPos, yPos, w, h) {
this.xPos= xPos;
this.yPos= yPos;
this.w= w;
this.h= h;
this.make= function() {
ctx.fillStyle = this.fill;
ctx.fillRect(this.xPos, this.yPos, this.w, this.h);
}
}
Upvotes: 0
Views: 54
Reputation: 10357
When you do something like this:
(function(){
return {}
})();
You are creating a Self Invoking Function that is, basically, a function that is created and then executed thanks to (). Ok, so your A function is self invoked and return a object containing some other objects. So your variable namespace.myCanvas will be the object that function returned.
And your B function is a Javascript Constructor, that (when used with new keyword) will return an object with xPos, yPos, w and h properties and a make method.
Hope it helps
EDIT This link can help you.. if your doubt is about function declaration and a function expression difference
Upvotes: 2