IT源码网

怎样拷贝对象

lxf 2021年03月09日 编程语言 425 0

方法一: 

function copyObject(orig) { 
  var copy = Object.create(Object.getPrototypeOf(orig)); 
  copyOwnPropertiesFrom(copy, orig); 
  return copy; 
} 
 
function copyOwnPropertiesFrom(target, source) { 
  Object 
    .getOwnPropertyNames(source) 
    .forEach(function (propKey) { 
      var desc = Object.getOwnPropertyDescriptor(source, propKey); 
      Object.defineProperty(target, propKey, desc); 
    }); 
  return target; 
}

 

方法二: 

function copyObject(orig) { 
  return Object.create( 
    Object.getPrototypeOf(orig), 
    Object.getOwnPropertyDescriptors(orig) 
  ); 
}

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!