深浅拷贝简单实现

88 阅读1分钟

深浅拷贝简单实现

Object.prototype.hasOwnProperty()

hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>深浅拷贝</title>
</head>

<body>
  <script>
    const person = {
      name: 'Maike',
      hobby: ['学习', ['篮球', '音乐']],
      function(a) { console.log(a) },
      date:new Date(),
      say:undefined
    }
    /**浅拷贝 */
    function clone(obj) {
      const target = {}
      for (let key in obj) {
        if (!target.hasOwnProperty(key)) {
          target[key] = obj[key]
        };
      };
      return target
    };
    /** 深度拷贝 */
    function deepClone(obj) {
      const clone = Array.isArray(obj) ? [] : {};
      if (obj && typeof obj === 'object') {
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === 'object') {
              clone[key] = deepClone(obj[key]);
            } else {
              clone[key] = obj[key];
            };
          };
        };
        return clone;
      }
    };
    const person1 = clone(person);
    const person2 = deepClone(person);
    person1.name = "Kaelin"
    person1.hobby[0] = '看电影'
    console.log('person1', person1)
    console.log('person', person)
    console.log('person2', person2)
  </script>
</body>

</html>