JavaScript Object.create in old IE

2020-05-08 20:53发布

问题:

Is there a way to make this code backwards compatible with IE6/7/8?

function Foo() {
    ...
}

function Bar() {
    ...
}

Bar.prototype = Object.create(Foo.prototype);

The main problem is Object.create errors, then crashes the browser.

So is there a function I can drop in to emulate the behavior of Object.create for old IE. Or how should I re-code the above to work around it?

回答1:

Pointy's comment as an answer

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Polyfill

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}

This polyfill covers the main use case which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account.