jsコピー継承

          定義: ディープ コピーは、元のオブジェクトの各属性を 1 つずつコピーするだけでなく、元のオブジェクトの各属性に含まれるオブジェクトを新しいオブジェクトに順番に再帰的にコピーするため、1 つのオブジェクトの変更は他のオブジェクトに影響しませ物体。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拷贝继承</title>
  </head>
  <body></body>
  <script>
    // 目的:让学生对象去继承人对象(人的构造函数和原型中的属性和方法)
    // 人的构造函数
    function Person(name, age) {
      this.name = name
      this.age = age
      this.eat = function () {
        console.log(this.name + '喜欢吃零食!')
      }
    }
    // 人的原型
    Person.prototype.sex = '女生'
    Person.prototype.sleep = function () {
      console.log(this.name + '喜欢睡懒觉!')
    }
    // 学生的构造函数
    function Student(score) {
      this.score = score
      this.study = function () {
        console.log(this.name + '喜欢努力学习!')
      }
    }
    // 学生的原型
    Student.prototype.className = '二班'
    Student.prototype.playLove = function () {
      console.log(this.name + '喜欢搞对象!')
    }
    var p1 = new Person('小花', 15)
    var stu = new Student(120)
    for (x in p1) {
      stu[x] = p1[x]
    }

    // 1、学生构造函数中的属性和方法
    console.log(stu.score)
    stu.study()
    // 2、学生原型中的属性和方法
    console.log(stu.className)
    stu.playLove()
    // 3、人的构造函数中的属性和方法
    console.log(stu.name)
    console.log(stu.age)
    stu.eat()
    // 4、人的原型中的属性和方法
    console.log(stu.sex)
    stu.sleep()
  </script>
</html>

オブジェクトのディープ コピー メソッドを使用するだけで、親クラスのコンストラクターとプロトタイプのすべてのプロパティとメソッドを継承できます。

おすすめ

転載: blog.csdn.net/weixin_47619284/article/details/126955496
おすすめ