如何在IE8中测试对象文字

时间:2013-07-15 16:46:42

标签: javascript prototype

目前正在使用:

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;
        })()
     )
  );

}

测试我们是否使用了对象文字。问题是IE8<无法使用getPrototypeOf,有没有人知道一个简单的解决方法?

1 个答案:

答案 0 :(得分:2)

改善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;
        };

尚未对其进行测试,但在大多数情况下,即使在IE8中也应该可以使用它。顺便说一下,您的isObjLiteral似乎可以简化为

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