javascript函数调用 - 嵌套函数

时间:2014-03-29 22:07:23

标签: javascript function

我正在尝试在js中实现以下内容:

    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是一个错误,我认为这是函数范围,对吧?如何调用push方法?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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));