ES5中定义的Object.create(proto)方法,会创建并返回一个新的对象,这个新的对象以传入的proto对象为原型。
语法如下:
Object.create(proto) (注:第二个参数忽略)
proto —— 作为新创建对象的原型对象
使用示例如下:
var a = Object.create({x: 1, y: 2});
alert(a.x);
Object.create在某些浏览器没有支持,请给出Object.create的兼容实现。
JavaScript 一道作业题,帮忙做一下
答案:2 悬赏:50 手机版
解决时间 2021-03-14 03:01
- 提问者网友:刺鸟
- 2021-03-13 18:31
最佳答案
- 五星知识达人网友:舍身薄凉客
- 2021-03-13 19:02
Object.create = Object.create || (function() {
var Temp = function(){},
hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
if (typeof O != 'object') {
throw TypeError('Object prototype may only be an Object or null');
}
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null;
if (arguments.length > 1) {
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
};
})();
var Temp = function(){},
hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
if (typeof O != 'object') {
throw TypeError('Object prototype may only be an Object or null');
}
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null;
if (arguments.length > 1) {
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
};
})();
全部回答
- 1楼网友:走死在岁月里
- 2021-03-13 19:12
object.create = object.create || (function() { var temp = function(){}, hasown = object.prototype.hasownproperty; return function(o) { if (typeof o != 'object') { throw typeerror('object prototype may only be an object or null'); } temp.prototype = o; var obj = new temp(); temp.prototype = null; if (arguments.length > 1) { var properties = object(arguments[1]); for (var prop in properties) { if (hasown.call(properties, prop)) { obj[prop] = properties[prop]; } } } return obj; };})();
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯