简体   繁体   中英

How to call two instances of same non-global JavaScript function with parameters

I am trying to call two different instances of a JavaScript function from HTML code, but I am confused about variable scope, the exact details of object instantiation, the necessity of returning the function to the browser, where and how to provide the function's parameters ... I tried different combinations of pieces of code from SO, yet to no avail. I am familiar with OOP, but not in its functional/JavaScript flavour.

I HTML I have something like:

<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>

In a JavaScript file called "JavaScript.js" I have something like:

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

I get an Uncaught TypeError: localInstance.myFunction is not a function error. What am I doing wrong?

I think you need to return your function so it can be accessible from the outside , something like this:

function globalFunction() {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM