Javascript Object.create not working in Firefox

自古美人都是妖i 提交于 2019-11-27 15:19:15

Object.create() is a new feature of EMCAScript5. Sadly it is not widely supported with native code.

Though you should be able to add non-native support with this snippet.

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

Which I believe is from Crockford's Javascript: The Good Parts.

Felix Kling

Object.create is part of ES5 and only available in Firefox 4.

As long as you are not doing any add-on development for browsers, you should not expect browsers to implement ES5 features (especially older browsers). You'd have to provide your own implementation then (like the own provided by @Squeegy).

I use this way(also working in 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!