为了账号安全,请及时绑定邮箱和手机立即绑定

迅雷面试题:深拷贝对象,除了原型上的属性?

迅雷面试题:深拷贝对象,除了原型上的属性?

慕工程0101907 2018-07-31 16:19:06
我的解决方法是:参考jquery中extend方法的实现,通过isPlainObject 函数判断该对象是否具有通过构造函数继承的原型上的属性。请问,我这个解决方法有什么问题吗? isPlainObject = function(obj) {          if (obj.constructor && !hasOwn.call(obj, "constructor")            && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {            return false;          }          var key;          for (key in obj) {          }          return key === undefined || hasOwn.call(obj, key);},                //测试,对于对象x不进行深拷贝function O() {  this.yyy = 'yyy';}function X() {  this.xxx = 'xxx';}X.prototype = new O();x = new X();obj1 = { a : 'a', b : 'b', y : '1'  };obj2 = {  x : { xxx : 'xxx', yyy : 'yyy' },  y : 'y' };var combineObj = $.extend(true,obj1,obj2);console.log(combineObj);
查看完整描述

2 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

刚好写了这方面的内容 
function Copy(p, c) {

var c = c || {};for (var i in p) {
  if (typeof p[i] === 'object') {
     c[i] = (p[i].constructor === Array) ? [] : {};
     Copy(p[i], c[i]);
  } else {
     c[i] = p[i];
  }
}return c;
}

a.key2 = ['小辉','小辉'];
var b={};
b = Copy(a,b); 
b.key2.push("大辉");
alert(b.key2); //小辉,小辉,大辉
alert(a.key2); //小辉,小辉


查看完整回答
反对 回复 2018-08-06
  • 2 回答
  • 0 关注
  • 1020 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信