list = list.next;并不能创建新的节点。 因为next属性是由prototype共享的,就是说所有next都是同一个对象
这样就可以了function Node (){}; Node.prototype.data = ""; Node.prototype.next = null; Node.prototype.create = function(){ return this.next = new Node; };var list = new Node; var header = list; for (var i = 10; i >= 0; i--) { list.data = i; list = list.create(); }; list.next = null;while(header.next != null) { alert(header.data); header = header.next; }
您好,您的代码我能明白,也试过,这就类似与工厂模式的写法了,我知道肯定能行。但是我不明白的就是,JS本身的prototype共享是怎么一回事,给我的感觉好像是我的链表里面就只有一个元素。Node.prototype.next = new Node,是没有调用自己的constructor吗?求细节描述啊大神们~这里我想了好久也没想明白,JS的内存机制把我搞乱了
list = list.next; 无效
因为next属性是由prototype共享的,就是说所有next都是同一个对象
Node.prototype.data = "";
Node.prototype.next = null;
Node.prototype.create = function(){
return this.next = new Node;
};var list = new Node;
var header = list;
for (var i = 10; i >= 0; i--) {
list.data = i;
list = list.create();
};
list.next = null;while(header.next != null) {
alert(header.data);
header = header.next;
}
这就要有个不断创建新节点的要求。
对象的prototype中的属性是所有实例共用一个的,而不是每个实例都创建自己的,类似java中的static属性
所以创建新节点的要求不能直接用prototype