William Orazi
William Orazi

Reputation: 1714

How to test for object literal in IE8

Currently using:

function isObjLiteral(_obj) {
  var _test  = _obj;
  return (  typeof _obj !== 'object' || _obj === null ?
     false :  (
        (function () {
           while (!false) {
              if (  Object.getPrototypeOf( _test = Object.getPrototypeOf(_test)  ) === null) {
                 break;
              }
           }
           return Object.getPrototypeOf(_obj) === _test;
        })()
     )
  );

}

to test if we're using an object literal. The problem is that IE8< cannot use getPrototypeOf, does anyone know an easy workaround?

Upvotes: 0

Views: 175

Answers (1)

Bergi
Bergi

Reputation: 664620

Improving this workaround:

if (typeof Object.getPrototypeOf !== "function")
    Object.getPrototypeOf = "".__proto__ === String.prototype
      ? function (obj) {
            if (obj !== Object(obj)) throw new TypeError("object please!");
            return obj.__proto__;
        }
      : function (obj) {
            if (obj !== Object(obj)) throw new TypeError("object please!");
            // May break if the constructor has been tampered with
            var proto = obj.constructor && obj.constructor.prototype;
            if (proto === obj) { // happens on prototype objects for example
                var cons = obj.constructor;
                delete obj.constructor;
                proto = obj.constructor && obj.constructor.prototype;
                obj.constructor = cons;
            }
            // if (proto === obj) return null; // something else went wrong
            return proto;
        };

Haven't tested it, but it should now work even in IE8 for the most cases. Btw, it seems like your isObjLiteral can be simplified to

function isPlainObject(obj) {
    if (obj !== Object(obj)) return false;
    var proto = Object.getPrototypeOf(obj);
    return !!proto && !Object.getPrototypeOf(proto);
}

Upvotes: 2

Related Questions