prototype.js 1.4,1.5中一个诡异的代码冲突,关于hash对象的,搞了一个小时才发现

Go_Rush 2006-08-21 02:58:18
其实不能说是bug

看我郁闷的代码

var hash={member:1,test:2,ids:3}
alert(hash.member)
alert($H(hash).inspect())
alert($H(hash).toQueryString())

hash.member实际是存在的

但是.inspect() 和 .toQueryString()却当它不存在


...全文
461 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
harryCom 2006-08-21
  • 打赏
  • 举报
回复
晕..没看到二楼的回复
harryCom 2006-08-21
  • 打赏
  • 举报
回复
不要用这些关键字就可以了:
Enumerable
{...}
each: {...}
all: {...}
any: {...}
collect: {...}
detect: {...}
findAll: {...}
grep: {...}
include: {...}
inject: {...}
invoke: {...}
max: {...}
min: {...}
partition: {...}
pluck: {...}
reject: {...}
sortBy: {...}
toArray: {...}
zip: {...}
inspect: {...}
map: {...}
find: {...}
select: {...}
member: {...}
entries: {...}
harryCom 2006-08-21
  • 打赏
  • 举报
回复
member是Enumerable对象的成员,会在这里被改写:
function $H(object) {
var hash = Object.extend({}, object || {});
Object.extend(hash, Enumerable); // member属性被Enumerable对同名属性的重写了
Object.extend(hash, Hash);
return hash;
}
return之前加个断点可以看到member的属性是:
hash.member
{...}
bindAsEventListener: {...}
bind: {...}
ice_berg16 2006-08-21
  • 打赏
  • 举报
回复
命名空间,或换名字
Go_Rush 2006-08-21
  • 打赏
  • 举报
回复
不知道各位有什么好的方法来解决这些 冲突
Go_Rush 2006-08-21
  • 打赏
  • 举报
回复
问题找到了

var Hash = {
_each: function(iterator) {
for (key in this) {

//这里 如果key是 "member",value将得到一个函数对象,而不是期望的值1
var value = this[key];
//所以下面这句将被执行
if (typeof value == 'function' ) continue;

var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},


member 是Enumerable的一个方法

Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray
});

而他,则把这个方法塞给了哈希对象

function $H(object) {
var hash = Object.extend({}, object || {});
Object.extend(hash, Enumerable);
Object.extend(hash, Hash);
return hash;
}

87,907

社区成员

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

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