2017-06-21 1 views
1

以下は私のコードです。 私は以下のようにそのメンバ関数と変数を持つクラスを持っています。 functionOne & functionTwoは簡潔なメソッドです。レキシカルJavascriptのconsiceメソッドでこれ

function MyUtils() { 
    this.actions = { 
     functionOne(param1, param2) { 
      console.log('This is first function which is not in action'); 
     }, 
     functionTwo(param1, param2) { 
      console.log('This is second function calling function three'); 
      //HOW DO I CALL functionThree HERE? 
      // I tried doing - this.functionThree() but not working 
     } 
    } 

    this.functionThree() { 
     console.log('This is third function'); 
    } 
} 

関数2が呼び出された場合、関数3を呼び出したいのですか?

+1

例には構文エラーがあります。最初に修正してください。 =) – evolutionxbox

+1

'my'を' MyUtils'の最初の行に格納することができます。例: 'var self = this;'、 'self.actions'、' self.functionThree'、そして 'そうです。 –

+0

「MyUtils」をどのようにインスタンス化していますか? – evolutionxbox

答えて

4

このキーワードなしでそれを行うことができ、これはJavaScriptでクロージャ構文を使用します。

function MyUtils() { 

    function functionThree() { 
     console.log('This is third function'); 
    } 

    this.actions = { 
     functionOne(param1, param2) { 
      console.log('This is first function which is not in action'); 
     }, 
     functionTwo(param1, param2) { 
      console.log('This is second function calling function three'); 
      //HOW DO I CALL functionThree HERE? 
      // I tried doing - this.functionThree() but not working 
      functionThree(); 

     } 
    } 


} 

、ここでは、REPLから出力されます(hereを発見した)

clear 
Native Browser JavaScript 

This is second function calling function three 
This is third function 
=> undefined 
+0

組み込みのスタックスニペットではなぜreplを使用するのですか? – evolutionxbox

1

これを試してみてください。

function MyUtils() { 
    var that = this; 

    this.actions = { 
    functionOne(param1, param2) { 
     console.log('This is first function which is not in action'); 
    }, 
    functionTwo(param1, param2) { 
     console.log('This is second function calling function three'); 
     that.functionThree(); 
    } 
    } 

    this.functionThree = function functionThree() { 
    console.log('This is third function'); 
    } 
} 

動作するかどうかを確認する:

var utils = new MyUtils(); 
utils.actions.functionTwo(); 

// Will output: 
// This is second function calling function three 
// This is third function 
関連する問題