原型执行没有被调用?

时间:2015-07-04 03:55:24

标签: javascript prototype breadth-first-search

我正在查看BFS的代码,我不明白为什么原型toString正在执行。往下看。如果没有此行,则每个节点都将作为对象返回。请帮我理解原型功能的用途。谢谢!

  function Node(info){

       this.info = info
       this.left = null;
       this.right = null;
       this.level = null; 
   }

   Node.prototype.toString = function() {
       console.log(this.info);
       console.log("activate"); 
       return this.info;

   }  

   function BFT(node) {

        node.level = 1;

        var queue = [node];

        var output = [];

        var current_level = node.level;

            while(queue.length > 0) {

                  current_node = queue.shift(); 
               console.log("before");
                  if(current_node.level > current_level) {
                console.log("?")
                         current_level++;
                         output.push("\n");

                  }  

                  output.push(current_node + " ");

                  if(current_node.left) {
                       current_node.left.level = current_level + 1; 
                       queue.push(current_node.left); 
                  }  

                  if(current_node.right) {
                       current_node.right.level = current_level + 1; 
                       queue.push(current_node.right); 
                  }  

            }

         return output.join("") 
   }



   var root = new Node(9);
       root.left = new Node(8);    
       root.right = new Node(7);

       root.left.left = new Node(2);
       root.left.right = new Node(4);

       root.right.left = new Node(6);
       root.right.right = new Node(8);

       root.left.left.left = new Node('a');
       root.left.left.right = new Node('b');

       root.left.right.right = new Node('c');

       console.log(BFT(root)) 

0 个答案:

没有答案