美文网首页
JS中的继承

JS中的继承

作者: David_Rao | 来源:发表于2020-01-10 14:57 被阅读0次
    <script>
        function Person(name, pets) {
            this.name = 'David';
            this.pets = pets;
        }
    
        Person.prototype = {
            constructor: Person,  // 注意这种写法constructor指针的修复
            run: function () {
                console.log('跑');
            }
        };
    
        function Student(num, name, pets) {
            //借助构造函数继承
            Person.call(this, name, pets);
            this.num = num;
        }
        // 寄生式继承
        function Temp() {}
        Temp.prototype = Person.prototype;
        var temp  = new Temp();
        Student.prototype = temp;
        temp.constructor = Student;
    
        // 注意:子类的原型方法要在继承后再写
        Student.prototype.study = function () {
            console.log('学');
        };
    
        var person = new Person();
        var student = new Student();
        person.run();  // 跑
        student.run();  // 跑
        student.study();  // 学
        console.log(Person.prototype.constructor);  // 经过修复后正确指向Person,否则指向Object
    </script>
    

    相关文章

      网友评论

          本文标题:JS中的继承

          本文链接:https://www.haomeiwen.com/subject/mhopactx.html