2013-07-15 49 views
0

目前正在使用:如何測試對象字面在IE8

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

}

測試,如果我們使用對象文本。問題是,IE不能使用getPrototypeOf,有誰知道一個簡單的解決方法?

+0

http://stackoverflow.com/questions/10919915/ie8-getprototypeof-method - 它花了2秒,谷歌找到 – Ian

+1

@Ian會是什麼實現...我看到了,但我只是得到一個無限循環... –

+0

也許我不明白你的問題 - 你真的試圖區分'{}'(一個對象字面量)和'new Object()'(不是對象文字)? – apsillers

回答

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