求穿越类问题。

ioriliao22 2011-12-01 04:06:26
今天想用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>

...全文
168 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ioriliao22 2011-12-01
  • 打赏
  • 举报
回复
终于解决,如下:

<script>
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>

默默不得鱼 2011-12-01
  • 打赏
  • 举报
回复
用闭包解决挺好
hookee 2011-12-01
  • 打赏
  • 举报
回复
这个protect member的问题,js解决起来比较困难。
要么用闭包把值直接固定到函数中,同时用类似工厂的模式来创建对象。
hch126163 2011-12-01
  • 打赏
  • 举报
回复
js 数组 自己就支持 pop 和push 方法
liangws 2011-12-01
  • 打赏
  • 举报
回复
我看楼主的push与pop看得很混乱。。
s.next.data='111';
如果不想用户直接访问,就将data与next改成私有变量

function stack(){
var data = '';
var next = null;
this.setData = function(_data){
//给出接口设置data
}
this.getData = function(_){
//给出接口访问data
}
}

87,990

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧