我在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
})();
关于javascript - 在JavaScript严格模式下对oop函数进行全局初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20245835/