kly*_*e_g 21 javascript jquery object internet-explorer-8
我遇到了一个插件的问题,该插件在jquery中使用object.create来创建日期下拉列表.我刚刚在IE 8中注意到它抛出了一个错误:
SCRIPT438: Object doesn't support property or method 'create'
Run Code Online (Sandbox Code Playgroud)
这是代码:
var dropdateobj = Object.create(dropdatefuncs);
dropdateobj.create(options, this);
$.data(this, 'dropdate', dropdateobj);
Run Code Online (Sandbox Code Playgroud)
对于IE8或更多跨浏览器兼容,有什么好处?
提前致谢!
pla*_*alx 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();
};
}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 20
有几个垫片提供这个,包括这个.
但请注意,无法完美填充,因为除其他外,它可以使用getter和setter创建不可枚举的属性或属性,这在所有ES5之前的浏览器上都无法做到.(您可以使用专有语法在某些ES5之前的浏览器上进行getter和setter,但不能在IE8上使用我不相信.)它只能是伪填充的.Object.create
但伪补丁会对你引用的用例有用.
只是为了完整性,这是一个可以填充的部件的简单版本:
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();
};
}
Run Code Online (Sandbox Code Playgroud)