拷贝对象

78 阅读1分钟

// 拷贝继承 // 把父对象的所有属性和方法,拷贝进子对象 // 将父对象的prototype对象中的属性,一一拷贝给Child对象的prototype对象

//  js写法
function Person() {}
            Person.prototype.foot = 2
            Person.prototype.head = 1
            Person.prototype.saySelf = function () {
                alert(`我有${this.foot}只脚和${this.head}+个头`)
            }
        
        function Student(name, no) {
            this.name = name
            this.no = no
        }

        // 拷贝继承
        function extend2(Child, Person) {
            var p = Person.prototype
            var c = Child.prototype
            for (var i in p) {
                c[i] = p[i]
            }
        }
        extend2(Student, Person)
        var stu1 = new Student('张三', 's001')
        alert(stu1.foot)
        alert(stu1.head)
        alert(stu1.name)
        alert(stu1.no)
        stu1.saySelf()