On May 26, 2:10 am, Kai Bansner <[EMAIL PROTECTED]> wrote:
> > Rewriting jQuery.each could fix most problems, still I'm not aware of
> > ALL the spots.
> > Modifying all the for..in SHOULD be enough.
>
> > --
> > Ariel Fleslerhttp://flesler.blogspot.com
>
> I like that ... any tips on how to detect which properties were added
> to the object via a Object.prototype? These are the value jQuery.each
> will need to skip.
>
> I gleaned this little snippet of code from another discussion on the
> internet which took place back in 2006, but it only helps when it's
> run before Prototype. It keeps all of the Prototype extended methods
> from showing up on new objects. I'm assuming my answer has something
> to do with .hasOwnProperty.
>
>         if( !Object.prototype.hasOwnProperty ) {
>              Object.prototype.hasOwnProperty = function( property ) {
>                  try {
>                      var prototype = this.constructor.prototype;
>                      while( prototype ) {
>                          if( prototype[ property ] ==
> this[ property ] ) {
>                              return false;
>                          }
>                          prototype = prototype.prototype;
>                      }
>                  } catch( e ) {}
>                  return true;
>              }
>          }

The above function does not implement hasOwnProperty correctly.  It
fails where:

1. the object has the property but its value is set to undefined
2. If the property is found on the prototype chain and has the same
value as the property on the object.
3. If the property on the prototype chain and the property on the
object reference the same object (the same as 2. above I guess).

The use of try..catch is probably not necessary, consider:

function xHOP(obj, property ) {
  var prototype = obj && obj.constructor &&
                  obj.constructor.prototype;
  while (prototype) {
    if (prototype[property] == obj[property]) {
      return false;
    }
    prototype = prototype.prototype;
  }
  return true;
}

// Some tests:

Object.prototype.b = 'fred';
Object.prototype.c = [1,2,3];
var obj = {};
obj.a = undefined;
obj.b = 'fred';
obj.c = Object.prototype.c;
alert(
          obj.hasOwnProperty('a') +  // true
   '\n' + xHOP(obj, 'a') +           // false, should be true
   '\n' + obj.hasOwnProperty('b') +  // true
   '\n' + xHOP(obj, 'b') +           // false, should be true
   '\n' + obj.hasOwnProperty('c') +  // true
   '\n' + xHOP(obj, 'c')             // false, should be true
);


The function may lead to very difficult to find errors.


--
Rob

Reply via email to