【问题标题】:Javascript Object.create not working in FirefoxJavascript Object.create 在 Firefox 中不起作用
【发布时间】:2011-07-09 02:52:30
【问题描述】:

我在 Firefox (3.6.14) 中总是遇到以下异常:

TypeError: Object.create is not a function

这很令人困惑,因为我很确定它是一个函数,并且代码在 Chrome 上按预期工作。

负责此行为的代码行如下:

Object.create( Hand ).init( cardArr );
Object.create( Card ).init( value, suit );

如果有人想查看所有代码,它来自扑克库 gaga.js:https://github.com/SlexAxton/gaga.js

也许有人知道如何让它在 Firefox 中运行?

【问题讨论】:

  • Alex 时不时地在 SO 上,所以也许他会回答 :-)

标签: javascript object-create


【解决方案1】:

我使用这种方式(也在 ECMAScript 3 中工作):-

function customCreateObject(p) {
   if (p == null) throw TypeError(); // p must be a non-null object
   if (Object.create)  // If Object.create() is defined...
     return Object.create(p);  // then just use it.
   var t = typeof p; // Otherwise do some more type checking
   if (t !== "object" && t !== "function") throw TypeError();
    function f() {}; // Define a dummy constructor function.
   f.prototype = p; // Set its prototype property to p.
   return new f(); // Use f() to create an "heir" of p.
}

var obj = { eid: 1,name:'Xyz' };
customCreateObject(obj);

【讨论】:

    【解决方案2】:

    Object.create 是 ES5 的一部分,仅在 Firefox 4 中可用。

    只要您不为浏览器进行任何附加开发,您就不应期望浏览器实现 ES5 功能(尤其是旧浏览器)。然后你必须提供你自己的实现 (like the own provided by @Squeegy)。

    【讨论】:

      【解决方案3】:

      Object.create() 是 EMCAScript5 的新特性。遗憾的是,本机代码并未广泛支持它。

      虽然您应该能够使用此 sn-p 添加非本地支持。

      if (typeof Object.create === 'undefined') {
          Object.create = function (o) { 
              function F() {} 
              F.prototype = o; 
              return new F(); 
          };
      }
      

      我相信这来自 Crockford 的 Javascript: The Good Parts

      【讨论】:

      • 我不推荐 Crockford 的 Object.create shim,因为 ES5 Object.create 方法可以做一些事情,而 没有办法在 ES3 上进行模拟环境... 使用这种填充程序,最终会产生两种不一致的实现,一种是原生的和预期的 ES5 方法,另一种是非标准的。 More info
      猜你喜欢
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      相关资源
      最近更新 更多