Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

You can now use Object.keys as normal such as Object.keys(myObject).length
Anonymous said...

Why are you doing Object.prototype.hasOwnProperty.call(o,p) instead of a simple o.hasOwnProperty(p)? Is it just in case that method is overridden in o?

Craig Constable said...

From memory o.hasOwnProperty(p) does not work correctly in IE < 9

Takeshi Okada said...

Hi,

Which information given by you on JavaScript-Browser Compatibility, very informative. So thanks for sharing your

knowledge. There are few other link that's also helpful for developers.


http://www.mindstick.com/Articles/643c4797-cd25-4dce-ac35-8107a88e3f0c/?JavaScript%20Browser%20Compatibility
http://www.tutorialspoint.com/javascript/javascript_browsers_handling.htm

Anonymous said...

thanks alot...

Post a Comment