【问题标题】:global initalization of oop function in javascript strict modejavascript严格模式下oop函数的全局初始化
【发布时间】:2013-11-27 15:01:58
【问题描述】:

我在 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 函数获取一些必须由用户输入的参数

【问题讨论】:

    标签: javascript jquery oop strict


    【解决方案1】:

    如果你想从一个函数初始化公共对象(虽然我不明白你为什么要这样做),你可以在公共范围内声明 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
    })();
    

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多