javascript 栈实现

function Stack() {
	var items = [];
	this.getItems = function(){
		return items;
	}
	//push方法
	this.push = function(el) {
		items.push(el);
	}
	//pop方法
	this.pop = function() {
		items.pop();
	}
	//栈顶
	this.peek = function(){
		return items[items.length - 1]
	}
	//栈是否为空
	this.isEmpty = function(){
		return items.length === 0;
	}
	//清空栈
	//这里是指向了新开辟的内存?不太清楚
	this.clear = function(){
		items = [];
	}
	//栈长度
	this.size = function(){
		return items.length;
	}
}

var stack = new Stack();
console.log(stack.isEmpty());
stack.push(5);
stack.push(8);
console.log(stack.peek());
stack.push(11);
console.log(stack.size());
console.log(stack.isEmpty());
stack.pop();
console.log(stack.size());

在Stack里面使用的是var items = [],而不是this.items = [] 这样做 new Stack()会发生什么。(闭包)

你可能感兴趣的:(javascript)