javascript函数调用-嵌套函数
我试图在js中实现以下功能: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){
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)代码>