0

目前使用:

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,有谁知道一个简单的解决方法?

4

1 回答 1

2

改进此解决方法

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);
}
于 2013-07-15T17:14:47.777 回答