0

i have this declaration of an object inside an Angular.js module:

    $scope.Stack = function () {
        this.top = null;
        this.size = 0;
    };

And when i call push method of that object i get undefined error:

    $scope.Stack.push = function (data) {
        return this.size;
    };

Why?

5
  • Push method is defined for an array. You should learn arrays and how to push data in an array. Commented Jul 2, 2015 at 4:51
  • @Vineet: no, push is my custom defined function and attached to that object Commented Jul 2, 2015 at 4:52
  • My guess is that you have hit against the this problem in JavaScript. The this instance when you are calling the push method is not the this that you are expecting. How are you calling push? Please provide more code. Commented Jul 2, 2015 at 5:08
  • @AndrewEisenberg: my whole code is this. i call it like this: $scope.Stack.push(1); Commented Jul 2, 2015 at 5:11
  • Yup. I see what's going on. Commented Jul 2, 2015 at 5:15

1 Answer 1

1

I don't think you are doing what you really want to do. You are creating a function called Stack and then the code:

$scope.Stack.push(1)

Invokes the push property on the Stack function (which doesn't exist). More likely, you want to create an instance of a Stack and call push on that.

var myStack = new $scope.Stack();
myStack.push(1);  // Yay!

This will work in most cases. But just beware that this is dynamically defined. I suggest you read up on this at MDN.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.