在写object.create(obj)兼容代码时,怎么写的代码在ie8下还是运行不了,看MDN的兼容浏览器,上面说的ie9是可以使用object.create,那么写的兼容代码在ie8下怎么不行呢?
Object.prototype.create = function(obj) {
if (typeof obj != 'object') {//如果 obj 参数不是 nll 或一个对象值,则抛出一个 TypeError 异常。
throw TypeError('Object prototype may only be an Object or null');
}
if(Object.prototype.create) {
return Object.prototype.create; //浏览器支持就直接返回
}else {
alert(11);
function Temp() {}//创建一个临时性的构造函数
Temp.prototype = obj; //传入的参数作为构造函数的原型
return new Temp(); //返回临时类型的一个新实例
}
};
var a = Object.create({x: 1, y: 2});
alert(a.x);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你的逻辑写错了。
第一行就给
Object.prototype.create指向了一个函数。所以调用时,这
if(Object.prototype.create)就判断已经有了create方法,直接返回了当前函数。解决办法就是
Object.prototype.createXXX = function(){};改个名字