簡體   English   中英

如何使用參數調用同一非全局JavaScript函數的兩個實例

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

我試圖從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>

在一個名為“ JavaScript.js”的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錯誤。 我究竟做錯了什么?

我認為您需要返回函數,以便可以從外部訪問它,如下所示:

function globalFunction() {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM