2016-09-23 6 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の落下を自分のクラスの関数に変更するだけで済むので、そこから処理します。

ご協力いただければ幸いです。あなたは試してみてください

var cClass = new ChildClass(); 

cClass = new ChildClass(); 

ローカルvarとは対照的に、そのためには、変数がクラス/関数の外に、世界的に利用できるようになります代わりに、宣言の

+1

コールバック関数

例)としてDoMathResponseを渡す約(関数(){DoMathRequest();});'に'.click(DoMathRequest)' – evolutionxbox

+0

また、javascriptはクラスフリーの言語であり、愚かな「クラス」のような構文です。 – evolutionxbox

+0

@evolutionxboxクラスがES6で追加されました:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class – Rotareti

答えて

1

方法.click `から、あなたのクリックイベントを簡略化することができる

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

宣言された変数。

関連する問題