如何使用参数调用相同的非全局JavaScript函数的两个实例

时间:2016-12-07 17:17:23

标签: javascript

我试图从HTML代码中调用两个不同的JavaScript函数实例,但我对变量范围,对象实例化的确切细节,将函数返回到浏览器的必要性,在何处以及如何提供函数的参数......我尝试了SO的不同代码组合,但无济于事。我熟悉OOP,但不熟悉它的功能/ JavaScript风格。

我是HTML我有类似的东西:

<script type="text/javascript" src="JavaScript.js"></script>

<script type="text/javascript">
    var localInstance = new globalFunction();
    localInstance.localFunction("someString", "someOtherString");

    var otherLocalInstance = new globalFunction();
    otherLocalInstance.localFunction("someString2", "someOtherString2");
</script>

在名为&#34; JavaScript.js&#34;的JavaScript文件中我有类似的东西:

function globalFunction() {
    var string;
    var otherstring;
    function localFunction(str, ostr) {
        string = str;
        otherstring = ostr;
        // do something more
    }
};

我收到Uncaught TypeError: localInstance.myFunction is not a function错误。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为您需要返回您的功能,以便可以从外部访问,如下所示:

function globalFunction() {

 var string;
 var otherstring;
 function localFunction(str, ostr) {
    string = str;
    otherstring = ostr;
    // do something more
 }
 return {
  localFunction: localFunction
 }};
相关问题