A Custom For In Statement
This page has the example: for (var name in buz) { if (buz.hasOwnProperty(name)) {} } To protect against seeing things in the prototype. This hack has made the 'for in' statem
Solution 1:
I think this is what you want
window.whatFor = function(obj,funct) {
for (var v in obj) {
if (obj.hasOwnProperty(v)) {
funct(v);
}
}
}
Then.
whatFor(sam, function (x) { alert(x); } );
Fiddle it up - because, why not?
Solution 2:
I really don't see why you're attaching whatFor
to the window
object. Doing so will make your code browser specific. You won't even be able to use it in web workers.
This is what I would do:
varglobal = typeofglobal !== "undefined" ? global :
typeof self !== "undefined" ? self : this;
global.whatFor = whatFor;
function whatFor(object, callback) {
var hasOwn = {}.hasOwnProperty.bind(object);
for (var property inobject)
if (hasOwn(property))
callback(property);
}
You may have noticed that instead of calling object.hasOwnProperty(property)
I'm calling hasOwn(property)
instead. This is because the hasOwnProperty
method may not exist in the prototype chain of the object.
Post a Comment for "A Custom For In Statement"