2017-06-21 1 views
1

Ci-dessous est mon code avec explication. J'ai une classe avec ses fonctions membres et variables comme ci-dessous. functionOne & functionTwo sont des méthodes concises.Lexique ceci dans les méthodes de consice en Javascript

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'); 
    } 
} 

Si la fonction deux est appelée alors je veux que la fonction trois soit appelée dans celle-ci?

+1

Vous avez des erreurs de syntaxe dans votre exemple. S'il vous plaît, réparez les premiers. =) – evolutionxbox

+1

Vous pouvez stocker le contexte externe 'this' dans la première ligne de' MyUtils', par exemple: 'var self = this;', alors vous pouvez utiliser en toute sécurité: 'self.actions',' self.functionThree', et bientôt. –

+0

Comment instanciez-vous 'MyUtils'? – evolutionxbox

Répondre

4

Vous pouvez le faire sans ce mot-clé, celui-ci utilise la syntaxe de fermeture en 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(); 

     } 
    } 


} 

et voici la sortie du rempl: (trouvé here)

clear 
Native Browser JavaScript 

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

Pourquoi utiliser repl lorsqu'un extrait de pile intégré le ferait? – evolutionxbox

1

Essayez ceci:

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'); 
    } 
} 

Pour vérifier si cela fonctionne:

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

// Will output: 
// This is second function calling function three 
// This is third function