ie8中不支持Object.create

问题描述 投票:21回答:3

我遇到了一个插件的问题,该插件在jquery中使用object.create来创建日期下拉列表。我刚刚在IE 8中注意到它抛出了一个错误:

SCRIPT438: Object doesn't support property or method 'create'

这是代码:

var dropdateobj = Object.create(dropdatefuncs);
dropdateobj.create(options, this);
$.data(this, 'dropdate', dropdateobj);

对于IE8或更多跨浏览器兼容,有什么好处?

提前致谢!

javascript jquery object internet-explorer-8
3个回答
37
投票

如果你需要Object.create,你很可能还需要依赖其他es5功能。因此,在大多数情况下,适当的解决方案是使用es5-shim

但是,如果Object.create是你唯一需要的东西而且你只用它来纯粹设置原型链,这里是一个轻量级的poly-fill,它不支持null作为第一个参数,并且不支持第二个properties参数。

这是规格:

15.2.3.5 Object.create(O [,Properties])

create函数使用指定的原型创建一个新对象。调用create函数时,将执行以下步骤:

如果Type(O)不是Object或Null则抛出TypeError异常。

设obj是创建一个新对象的结果,好像是通过表达式new Object(),其中Object是具有该名称的标准内置构造函数

将obj的[[Prototype]]内部属性设置为O.

如果参数Properties存在且未定义,则将自己的属性添加到obj,就好像通过调用带有参数obj和Properties的标准内置函数Object.defineProperties一样。

返回obj。

这是轻量级实现:

if (!Object.create) {
    Object.create = function(o, properties) {
        if (typeof o !== 'object' && typeof o !== 'function') throw new TypeError('Object prototype may only be an Object: ' + o);
        else if (o === null) throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");

        if (typeof properties != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");

        function F() {}

        F.prototype = o;

        return new F();
    };
}

20
投票

有几个垫片提供这个,包括this one

请注意,Object.create不能完美地填充,因为除了其他功能之外,它还可以使用getter和setter创建不可枚举的属性或属性,这在所有ES5之前的浏览器上都无法做到。 (您可以使用专有语法在某些ES5之前的浏览器上进行getter和setter,但不能在IE8上使用我不相信。)它只能是伪填充的。

但伪补丁会对你引用的用例有用。

只是为了完整性,这是一个可以填充的部件的简单版本:

if (!Object.create) {
    Object.create = function(proto, props) {
        if (typeof props !== "undefined") {
            throw "The multiple-argument version of Object.create is not provided by this browser and cannot be shimmed.";
        }
        function ctor() { }
        ctor.prototype = proto;
        return new ctor();
    };
}

0
投票

This will make Object.create() work in IE 8.

我尝试了垫片/假,但这对我不起作用。

if (typeof Object.create !== 'function') {
 Object.create = function(o, props) {
  function F() {}
  F.prototype = o;

  if (typeof(props) === "object") {
   for (prop in props) {
    if (props.hasOwnProperty((prop))) {
     F[prop] = props[prop];
    }
   }
  }
  return new F();
 };
}
© www.soinside.com 2019 - 2024. All rights reserved.