旧的IE中的JavaScript Object.create [英] JavaScript Object.create in old IE
问题描述
有没有办法让这个代码向后兼容IE6 / 7/8?
Is there a way to make this code backwards compatible with IE6/7/8?
function Foo() {
...
}
function Bar() {
...
}
Bar.prototype = Object.create(Foo.prototype);
主要问题是 Object.create
错误,然后崩溃浏览器。
The main problem is Object.create
errors, then crashes the browser.
所以我可以插入一个函数来模拟 Object.create
对于旧IE。或者我应该如何重新编写上面的代码来解决它?
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?
推荐答案
Pointy的评论作为答案
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();
};
}
此polyfill涵盖了创建一个新对象的主要用例,已经选择了原型,但没有考虑第二个参数。
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.
这篇关于旧的IE中的JavaScript Object.create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!