2014-03-29 133 views
0

我试图实现以下的JS:javascript函数调用 - 嵌套函数

function Stack() { 
     var top = null; 
     var count = 0; 

     //returns the total elements in an array 
     this.getCount = function() { 
      return count; 
     } 

     this.Push = function(data){ 
      var node = { 
       data: data, 
       next: null 
      } 

      node.next = top; 
      top = node; 
      count++; 

      console.log("top: " + top,"count: " + count); 
     } 

    } 

    Stack.Push(5); 

到Stack.Push该呼叫被抛出一个错误,我认为这是函数的范围,是吧?我怎样才能打电话给推送方法?

+0

'VAR某物=新的堆栈(;某人(5);' – akinuri

回答

1

您需要创建函数的对象实例

var stack = new Stack(); 
stack.push(5); 
+0

哦,是的.. !!谢谢! – pj013

0

您必须创建的Stack一个实例:)

function Stack() { 
    var top = null; 
    var count = 0; 

    //returns the total elements in an array 
    this.getCount = function() { 
     return count; 
    } 

    this.Push = function(data){ 
     var node = { 
      data: data, 
      next: null 
     } 

     node.next = top; 
     top = node; 
     count++; 

     console.log("top: " + top,"count: " + count); 
    } 

} 
var instance = new Stack(); 
console.log(instance.Push(5));