2011-03-04 19 views
4

工作,我總是在Firefox以下異常(3.6.14):的Javascript的Object.create不能在Firefox

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中工作?

+0

亞歷克斯是所以現在再等等,也許他會回答:-) – Pointy 2011-03-04 20:54:27

回答

13

Object.create()是EMCAScript5的新功能。可悲的是,它並沒有得到本地代碼的廣泛支持。

雖然您應該可以使用此片段添加非本機支持。

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

我相信這是從Crockford的的Javascript:好的部分

+0

謝謝!這解決了這個問題。 – dominos 2011-03-04 20:59:06

+5

我不會推薦Crockford的'Object.create'墊片,因爲有些東西是ES5 Object.create'方法可以做的,並且有**無法在ES3環境中模擬** ...有了這個一種墊片最終會導致兩種不一致的實現,即本機和期望的ES5方法,以及非標準方法。 [更多信息](http://stackoverflow.com/questions/3830800/#3844768) – CMS 2011-03-04 21:04:00

+0

好點。感謝您的鏈接。 – 2011-03-04 21:46:12

0

Object.create是ES5的一部分,並且只適用於火狐4

只要你沒有做任何的瀏覽器插件上發展,你不應該指望瀏覽器來實現ES5功能(尤其是舊版本瀏覽器)。您必須提供您自己的實施(like the own provided by @Squeegy)。

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