Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript函数调用-嵌套函数_Javascript_Function - Fatal编程技术网

javascript函数调用-嵌套函数

javascript函数调用-嵌套函数,javascript,function,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){

我试图在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方法?

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

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

必须创建
堆栈的实例

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));
var sth=newstack();推(5)