今天想用js实现一个栈,原始代码如下:<script>
function stack(){
this.data='';
this.next=null;
this.push=function(d){
var tmp=new stack()
tmp.data=d;
tmp.next=this.next;
this.next=tmp;
}
this.pop=function(){
var tmp=new stack()
tmp=this.next;
this.next=tmp.next;
return tmp.data;
}
} var s=new stack();
s.push("10");
s.next.data='111'; //问题在这里,我不希望用户可以这样直接访问类的next或data属性。
s.push("20");
s.push("30");
alert(s.pop());
alert(s.pop());
alert(s.pop());
</script>
function stack(){
this.data='';
this.next=null;
this.push=function(d){
var tmp=new stack()
tmp.data=d;
tmp.next=this.next;
this.next=tmp;
}
this.pop=function(){
var tmp=new stack()
tmp=this.next;
this.next=tmp.next;
return tmp.data;
}
} var s=new stack();
s.push("10");
s.next.data='111'; //问题在这里,我不希望用户可以这样直接访问类的next或data属性。
s.push("20");
s.push("30");
alert(s.pop());
alert(s.pop());
alert(s.pop());
</script>
解决方案 »
- 请问一下, 表单如何一有输入就处理?
- js中关于setTimeout()与setInterval()的异议
- jquery validate验证问题,大家帮我看看哪错了
- 以下程序实现后,<div id="myys"></div>里的按钮可以点击,但没法选中,求解
- Extjs GridPanel分组可以禁止缩放功能吗
- confirm的使用?
- 如何有选择性的打印,比如打印页面某个div里或者table里的内容?
- 我刚学jb8,按照参考书上写'hello world'的开始编程,怎么出错!!!大家帮我!!!
- js里如何同时把'/'和'\'替换成'\\'?
- 如何让文本框输入数字和小数点,还有减号!谢谢
- 求《省市高中》《省市初中》联动控件,或者《省市高中》《省市初中》完整数据
- 求aptana工具的详细使用方法
s.next.data='111';
如果不想用户直接访问,就将data与next改成私有变量function stack(){
var data = '';
var next = null;
this.setData = function(_data){
//给出接口设置data
}
this.getData = function(_){
//给出接口访问data
}
}
要么用闭包把值直接固定到函数中,同时用类似工厂的模式来创建对象。
function stack(){
var next=null;
this.push=function(d){
var tmp=new stack()
tmp.data=d;
tmp.next=next;
next=tmp;
}
this.pop=function(){
var tmp=new stack()
tmp=next;
next=tmp.next;
return tmp.data;
}
} var s=new stack();
s.push("10");
alert(s.next);
s.push("20");
s.push("30");
alert(s.pop());
alert(s.pop());
alert(s.pop());
</script>