2016-09-23 45 views
0

我通常不是JavaScript的人,所以這對我來說有點陌生。在主腳本中創建一個JavaScript類函數調用函數

我試圖做一個JavaScript類,可以在主腳本中調用函數。這裏有一個例子:

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> 
     <script type="text/javascript"> 

      function ChildClass(){ 

       this.X; 
       this.Y; 

       this.DoMath = function(){ 

        var answer = this.X + this.Y; 

        // I'm trying to pass the answer variable back to the "DoMathResponse" function. Currently, the "DoMathRequest" 
        // is passed to another domain via CDM, processed, then the response is routed back to the "DoMathResponse" function. 
        // This class is intended to replace the CDM call with as little modification to the existing code as possible, so I 
        // can't simply return the answer variable. 

        pClass.DoMathResponse(answer); //<-- I want to do something like this 
       }; 
      } 

      $(document).ready(function(){ 

       var cClass = new ChildClass(); 
       cClass.X = 8; 
       cClass.Y = 5; 


       var DoMathRequest = function(){ 

        cClass.DoMath(); 
       }; 

       var DoMathResponse = function(answer){ 

        alert(answer); 
       }; 


       // Button Click Event Handler 
       $("#btn").click(function(){DoMathRequest();}); 

      }); 

     </script> 
    </head> 

    <body> 
     <div id="btn">Click Me</div> 
    </body> 
</html> 

這是可能與JavaScript?現有代碼使用CDM調用另一個域,並試圖用類替換跨域調用。我想通過儘可能少地修改原始代碼來完成此操作。我完全控制了ChildClass,但其他人使用現有的代碼,所以我想調用與跨域消息路由到的功能相同的功能。這樣,我們只需要將CDM下降到我班的功能,然後從那裏處理。

任何幫助,將不勝感激。

+1

點擊事件可以被簡化,從'。點擊(函數(){DoMathRequest();});'來'.click(DoMathRequest)' – evolutionxbox

+0

另外,javascript是一種免費的語言,有類似語法的愚蠢「類」。 – evolutionxbox

+0

@evolutionxbox類在ES6中添加:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class – Rotareti

回答

1

如何傳遞DoMathResponse作爲一個回調函數

EG)

function ChildClass(){ 
     this.X; 
     this.Y; 

     this.DoMath = function(onComplete) { 
         var answer = this.X + this.Y; 
         onComplete (answer); 
     }; 
} 

$(document).ready(function(){ 
     var cClass = new ChildClass(); 
     cClass.X = 8; 
     cClass.Y = 5; 

var DoMathResponse = function(answer){ 
     alert(answer); 
}; 

var DoMathRequest = function(){ 
     cClass.DoMath(DoMathResponse); 
}; 
+0

我喜歡這個回答最棒的。我將其標記爲答案。謝謝!!! –

0

,而不是聲明:

var cClass = new ChildClass(); 

你應該嘗試:

cClass = new ChildClass(); 

這樣會讓變量可以全局,出類/函數的,而不是本地var聲明的變量。

相關問題