melanke / Watch.JS

watch the changes of any object or attribute
Other
2.14k stars 219 forks source link

Use standard for when iterating over array items and add hasOwnProperty check for objects #45

Open Maluen opened 11 years ago

Maluen commented 11 years ago

Otherwise strange things happen if the application adds properties to the Array prototype, another solution is to insert an "hasOwnProperty" check inside the "for in" loop, but the former is a better fix for arrays imho.

For example, in the loop function, starting from row 342:

for(var i in lengthsubjects){

    var subj = lengthsubjects[i];
    var difference = getObjDiff(subj.obj[subj.prop], subj.actual);

    // ...
};

In this case, the loop will iterate also over non owned-properties, i.e. property added to the Array prototype.

So the code should be changed to:

for(var i=0,l=lengthsubjects.length; i<l; i++) {

    var subj = lengthsubjects[i];
    var difference = getObjDiff(subj.obj[subj.prop], subj.actual);

    // ...
};

Same apply when iterating over objects, but in this case an "obj.hasOwnProperty(prop)" check inside the "for in" loop is required.

melanke commented 11 years ago

good point

I will fix it

thx

gregkaczan commented 11 years ago

Indeed "hasOwnProperty" is mandatory, otherwise i got error: Uncaught TypeError: Cannot read property 'undefined' of undefined