After some studying I have found out four ways you can initialize an object in Javascript:
1.
var Game = { // I guess everything here is made public?
canvas : document.createElement("canvas"),
render : function(){
}
}
2.
var Game = function(){ //if this function isn't a self invoking one, how should it be called?
var canvas = document.createElement("canvas");
return {
render : function(){ // why this does not work when being called? says it's undefined
alert("a");
}
}
}
3.
var Game = (function(){
var canvas = document.createElement("canvas");
function init_properties(){ // why is this not called?
alert("test");
}
return {
// whatever you want to be made public
render : function(){
alert(canvas);
}
}
}) ()
4.
function Game(){
var privateVar = 10;
this.publicVar = 20;
this.render = function(){
}
}
Besides the questions in the comments, in what case should each one be used? Are there noticeable performance difference when using one over another?
Your first and third methods return objects, your second and fourth methods are instantiation functions. The third is the same as the second, but is immediately called to resolve to the object. This is called an immediate invoked function expression (IIFE). It's used to create private variables accessible to the returned object's methods without needing to separately defined the initialization function. There's really no practical reason to do this.
There are two ways you should instantiate objects in JavaScript: directly and through an initialization function.
You want to use direct instantiation when you don't need to keep track of private variables in association with the object. If you do need private variables, instantiate the object by calling an initialization function returning the object.
Direct(your first method):
const Game = {
canvas : document.createElement("canvas"),
render : () => alert('a')
}
Through an initialization function(your second and fourth methods):
const initGame = () => {
const privateCounter = 0
const canvas = document.createElement("canvas")
return {
render: () => alert('a')
}
}
const Game = initGame()