2015-11-24 52 views
0

遇到了一些有關我的函數聲明範圍的奇怪的JavaScript問題。在我的BST函數中,我可以調用函數node而沒有問題。但在我的createMinimalHeightBST函數中,當我嘗試調用BST函數時出現錯誤。我的createMinHeightBST函數中的JavaScript函數聲明範圍

錯誤說:

TypeError: BST is not a function

請參閱行內容註釋作品DOESNT作品


CODE

var BST = new BST(10); 

console.log(BST.root); 


function node(data) { 
    this.data = data; 
    this.right = null; 
    this.left = null; 
} 

function BST(root_data) { 
    this.root = root_data === undefined ? root_data : new node(root_data); //WORKS 
    this.addNode = function(node, root) { 
     if (root === undefined) return this.addNode(node, this.root); 
     if (!root) { 
      root = node; 
      return; 
     } 
     if (root.data > node.data) { 
      if (!root.left) { 
       root.left = node; 
       return; 
      } 
      return this.addNode(node, root.left); 
     } 
     if (!root.right) { 
      root.right = node; 
      return; 
     } 
     return this.addNode(node, root.right); 
    }; 
} 

var test = [2, 5, 9, 21, 50, 88]; 

function createMinimalHeightBST(sorted_arr) { 
    var mid = Math.floor(sorted_arr.length/2); 
    var minimal_height_tree = new BST(sorted_arr[mid]); // DOESNT WORK 

    for (var i=0; i<sorted_arr.length; i++) { 
     if (i !== mid) minimal_height_tree.addNode(sorted_arr[i]); 
    } 

    return minimal_height_tree; 
} 

console.log(createMinimalHeightBST(test)); 

回答

0

定義構造函數之後var BST = new BST(10);並請改變變量名稱不同的東西

1

固定碼:現在沒有與功能VS變量聲明混亂一線 VAR BST =新的BST_Function(10);

console.log(BST.root); 

    function node(data) { 
     this.data = data; 
     this.right = null; 
     this.left = null; 
    } 

    function BST_Function(root_data) { 
     this.root = root_data === undefined ? root_data : new node(root_data); //WORKS 
     this.addNode = function (node, root) { 
      if (root === undefined) return this.addNode(node, this.root); 
      if (!root) { 
       root = node; 
       return; 
      } 
      if (root.data > node.data) { 
       if (!root.left) { 
        root.left = node; 
        return; 
       } 
       return this.addNode(node, root.left); 
      } 
      if (!root.right) { 
       root.right = node; 
       return; 
      } 
      return this.addNode(node, root.right); 
     }; 
    } 

    var test = [2, 5, 9, 21, 50, 88]; 

    function createMinimalHeightBST(sorted_arr) { 
     var mid = Math.floor(sorted_arr.length/2); 
     var minimal_height_tree = new BST_Function(sorted_arr[mid]); // DOESNT WORK 

     for (var i = 0; i < sorted_arr.length; i++) { 
      if (i !== mid) minimal_height_tree.addNode(sorted_arr[i]); 
     } 

     return minimal_height_tree; 
    } 

    console.log(createMinimalHeightBST(test));