2013-03-17 5 views
2

J'ai la fonction suivante dans un objet prototype:fonction récursion prototype rappel

EmptyChild:function(node) 
{ 

    if (Array.isArray(node.children)) { 
     node.children = node.children.filter(
      function(child) { 
       if (child['id'] =="" || child.length) { 
        return false; 
       } else { 
        this.EmptyChild(child); 
        return true; 
       } 
      } 
     ); 
    } 
} 

mais je reçois l'erreur suivante:

Uncaught TypeError: Object [object global] has no method 'EmptyChild' 

Comment puis-je résoudre ce problème?

Répondre

3

this est l'objet global dans votre rappel. Vous devez enregistrer le vôtre dans une variable ou le transmettre à filter.

Voir la documentation:

If a thisObject parameter is provided to filter, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.

Ainsi, votre code peut être:

if (Array.isArray(node.children)) { 
     node.children = node.children.filter(
      function(child) { 
       if (child['id'] =="" || child.length) { 
        return false; 
       } else { 
        this.EmptyChild(child); 
        return true; 
       } 
      } 
     , this); // <===== pass this 
    } 
+0

merci! J'ai appris quelque chose de nouveau aujourd'hui. –