首页 > 文章列表 > Javascript如何用原型对象继承父类型

Javascript如何用原型对象继承父类型

原型 JavaScript
255 2022-08-06

1、将子类所共享的方法提取出来,让子类的prototype 原型对象 = new 父类()。子类原型对象等于是实例化父类。

因为父类实例化之后另外开辟空间,就不会影响原来父类原型对象

2、将子类的constructor重新指向子类的构造函数。

实例

// 父构造函数
        function Father(uname, age) {
            this.name = uname;
            this.age = age;
        }
        Father.prototype.earn = function() {
                console.log(10000);
            }
            // 子构造函数
        function Son(uname, age, score) {
            Father.call(this, uname, age);
            this.score = score;
        }
 
        Son.prototype = new Father();
        Son.prototype.constructor = Son;
        Son.prototype.exam = function() {
            console.log("考试");
        };
 
        var son = new Son('ldh', 18, 100);
        console.log(son);

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。