The hasOwnProperty method lets you know if a property is directly on an instance of an object or inherited from it's prototype chain.
Consider the following
function ObjWithProto() {
this.foo = 'foo_val';
}
ObjWithProto.prototype = {bar: 'bar_val'};
var dict = new ObjWithProto();
dict.foobar = 'foobar_val';
i.e. you have an Object dict
with properties foo
and foobar
that also inherits a property bar
from it's prototype chain.
Now run it through (a modified version of) your code
function forEach(dict) {
var key;
for (key in dict) {
if ( dict.hasOwnProperty(key) ) console.log('has', key, dict[key]);
else console.log('not', key, dict[key]);
}
}
forEach( dict );
You will see
has foo foo_val
has foobar foobar_val
not bar bar_val
This lets you separate properties that an object has itself and those it has inherited (which are usually methods that aren't relevant to the loop)
Furthermore, if you now do dict.bar = 'new_bar_val';
, the last result will change to has bar new_bar_val
, letting you distinguish even between properties of the same name as those inherited.
key
is global where is this code from, can you post a link to it? – elclanrs Oct 4 '12 at 20:58var
in for in loops, edit: oh, I just read that it is not his code... interesting – ajax333221 Oct 4 '12 at 22:08var
. – elclanrs Oct 4 '12 at 22:11