javascript严格模式下oop函数的全局初始化

global initalization of oop function in javascript strict mode

本文关键字:函数 全局 初始化 oop 模式 javascript      更新时间:2023-12-02

我在javascript中有一个oop函数,如下所示:

'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();
}

如何初始化oopFunc对象一次(像全局变量一样)并使用这样的方法?:

'use strict';
function oopFunc(){
    this.oopMethod(){
        console.log('hey it works');
    }
}
function initOopfunction(){
    init = new oopFunc();
}
function foo(){
    init.oopMethod();
}
function bar(){
    init.oopMethod();
}

我必须将可变参数传递给该方法,但我不想每次使用时都初始化它的新对象

编辑

我需要在另一个函数中初始化该函数,因为oop函数会得到一些参数,这些参数必须由用户输入

如果你想从一个函数初始化公共对象(尽管我不知道你为什么要这么做),你可以在公共作用域中声明var,然后从其他地方初始化它。

'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();

请在此处查看:http://jsfiddle.net/8eP6J/

'use strict';的要点是,当您不使用var声明变量时,它可以防止创建隐式全局变量。如果您显式地声明变量,那么就可以开始了。

慢慢来,阅读以下内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode

此外,我建议您将代码封装在自动执行的函数中,以免污染全局范围,并避免与站点中可能运行的其他脚本发生冲突。理想情况下,整个应用程序应该只存在于一个全局变量中。有时你甚至可以避免这种情况。类似以下内容:

(function () {
    'use strict';
    // the rest of your code
})();