【发布时间】:2011-12-26 11:32:22
【问题描述】:
我正在用 Node.js 编写一个简单的原型,其中包含一些我可能在使用该原型的对象中需要的辅助方法。我想要的一种方法是 jQuery 的.each() 的实现。我在他们的开发版本中查看了 jQuery 的实现,并尝试在我的简化版本中模拟它。
// Loop through the object using a callback
BaseProto.prototype.each = function (cb, args) {
var obj = this.get(), // Get our object as a plain object
prop;
/** Code to make sure the the args passed are actually an array **/
if (typeof cb === "function") {
// For each property in our object
for (prop in obj) {
// Apply the callback to the object's property and pass
// the index, the property, and whatever else as arguments
if (cb.apply(obj[prop], [ prop, obj[prop] ].concat(args)) === false) {
// Get out if the function returns false
break;
}
}
}
// Reset our object with the new one
return this.reset(obj);
};
问题在于,虽然回调肯定会被触发,但它对对象的属性没有任何影响。无论我在回调中做什么,更改都保留在回调的范围内。
这是一个我一直在测试的简单回调示例。
var BaseProtoTestObj = new BaseProto();
/** Set some properties to BaseProtoTestObj **/
function cb1 ( key, val ) {
var prop;
key = key.toString() + " Callbacked";
val = val.toString() + " Callbacked";
for (prop in this) {
this[prop] = this[prop].toString() + " Callbacked";
}
}
// Doesn't have any effect on BaseProtoTestObj
BaseProtoTestObj.each(cb1);
我可以看到 jQuery 的 .each() 中还有很多事情要做,但据我所知,它是为了优化以及迭代数组和对象的能力。
最后,我的问题很简单。 jQuery 正在做什么来影响属性,我不在我的.each() 中?
编辑
我想另一个问题是我的逻辑是否根本上是错误的,而您不能以这种方式修改对象的属性。
【问题讨论】:
-
可以看到jQuery的.each()here。它在第 610 行。
标签: javascript node.js iteration