4

我总是在 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 中运行?

4

3 回答 3

13

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

尽管您应该能够使用此代码段添加非本机支持。

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

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

于 2011-03-04T20:53:21.807 回答
0

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

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

于 2011-03-04T20:53:03.647 回答
0

我使用这种方式(也在 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);
于 2016-01-24T08:39:38.310 回答