global initalization of oop function in javascript strict mode

226 views Asked by At

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

1

There are 1 answers

0
bgusach On BEST ANSWER

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.

'use strict';

var myObj;

function ObjConstructor() {
    this.hey = function () {alert ('hey');};
}

function init() {
     myObj = new ObjConstructor();   
}

function another() {
     init();  // Common object initialized
     myObj.hey();
}

another();

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 with var. 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:

(function () {
    'use strict';

    // the rest of your code
})();