简体   繁体   中英

javascript function call - nested functions

I am trying to implement the following in 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);

The call to Stack.Push is throwing an error, I think it is function scoping, right? How can I make the call to the push method?

You need to create an object instance of the function

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

You must create an instance of 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM