On 11/04/2011, at 05:14, Mark S. Miller wrote:
> 
> On Apr 10, 2011, at 22:18 , David Herman wrote:
> 
> > function getDefiningObject(obj, key) {
> >    if (!(key in obj))
> >        throw new Error("key " + key + " not found");
> >    while (!obj.hasOwnProperty(key))
> 
> That should be
> 
>          while (!{}.hasOwnProperty.call(obj, key))
> 
> which works even if obj has an own property named 'hasOwnProperty'.

And also because that would work for null too, unlike (null).hasOwnProperty( 
key ) that would throw "TypeError: 'null' is not an object (evaluating 
'(null).hasOwnProperty')", and null is at the end of the prototype chain of all 
objects...

Here's another take on it:

function getDefiningObject (o, key) {
  do {
    if ( {}.hasOwnProperty.call(o, key) ) break;
  } while ( o = Object.getPrototypeOf(o) );
  return o;
}

getDefiningObject([1,2], 'length')
[1, 2]
getDefiningObject([1,2], 'pop')
[]
getDefiningObject([1,2], 'valueOf')
Object
getDefiningObject([1,2], 'none')
null
-- 
Jorge.
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to