I have an oop function in javascript like this:
'use strict';
function oopFunc(){
this.oopMethod(){
console.log('hey it works');
}
}
function foo(){
var init = new oopFunc();
init.oopMethod();
}
function bar(){
var again = new oopFunc();
again.oopMethod();
}
how can I initalize the oopFunc object just once (like a global variable) and use the methods like this?:
'use strict';
function oopFunc(){
this.oopMethod(){
console.log('hey it works');
}
}
function initOopfunction(){
init = new oopFunc();
}
function foo(){
init.oopMethod();
}
function bar(){
init.oopMethod();
}
I have to pass variable parameters to the method but I dont want to initalize a new Object of it for each time I want to use it
EDIT
I need to initalize the function within a other function because the oop function get some parameters which must be typed in by the user
If you want to initialize the common object from a function (although I dont undestand why you want to do that), you can just declare the var in the common scope, and initialize it from somewhere else.
Check it here: http://jsfiddle.net/8eP6J/
The main point of
'use strict';
, is that it prevents the creation of implicit globals when you don't declare a variable withvar
. If you declare the variable explicitly, you are good to go.Take your time and read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
Moreover, I would recommend you to wrap your code within a autoexecuted function not to pollute the global scope and avoid collisions with other scripts that might be running in the site. Ideally your whole application should live only in one global variable. And sometimes you can even avoid that. Something like the following: