JS中的继承

2020-01-10  本文已影响0人  David_Rao
<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>
上一篇 下一篇

猜你喜欢

热点阅读