Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - Object.create not supported in ie8

I came across an issue with a plugin that uses object.create in jquery to create a date dropdown. I just noticed in IE 8 that it is throwing an error of:

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

Here is the code:

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

What is a good work around for IE8 or more cross browser compatible?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you need Object.create, there are good chances you may need to rely on other es5 features as well. Therefore, in most cases the appropriate solution would be to use es5-shim.

However, if Object.create is the only thing you need and you only use it to purely setup the prototype chain, here's a lightweight poly-fill that doesn't support null as the first argument and doesn't support the second properties argument.

Here's the spec:

15.2.3.5 Object.create ( O [, Properties] )

The create function creates a new object with a specified prototype. When the create function is called, the following steps are taken:

If Type(O) is not Object or Null throw a TypeError exception.

Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name

Set the [[Prototype]] internal property of obj to O.

If the argument Properties is present and not undefined, add own properties to obj as if by calling the standard built-in function Object.defineProperties with arguments obj and Properties.

Return obj.

Here's the lightweight implementation:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...