0

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?

asked Mar 29, 2014 at 22:07
1
  • var sth = new Stack(); sth.Push(5); Commented Mar 29, 2014 at 22:13

2 Answers 2

1

You need to create an object instance of the function

var stack = new Stack();
stack.push(5);
answered Mar 29, 2014 at 22:13

Comments

0

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));
answered Mar 29, 2014 at 22:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.