JavaScript函数继承

在ES6中有了继承,使用extends关键字就能实现。但这里讲的讲的不是这种,而是ES6之前的几种实现继承的方式。

(一)原型继承

ECMAScript中将原型链作为实现继承的主要方法。其基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法。

例如:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script>
            function Person(){
                this.name = 'zs';
                this.age = 18;
                this.sex = '男';
            }
            
            function Student(){
                this.score = 100;
            }
            
            Student.prototype = new Person();
            Student.prototype.constructor = Student;
            
            var s1 = new Student();
            console.log(s1.constructor);
            console.dir(s1);
            
            
            //原型继承 :不能设置构造函数的参数
        </script>
    </body>
</html>

(二)借用构造函数

在解决原型中包含引用类型值所带来的问题中,使用借用构造函数技术来解决。借用构造函数的基本思想,即在子类型构造函数的内部调用超类型构造函数。函数只不过是在特定环境中执行代码的对象,因此通过使用call()方法可以在新创建的对象上执行构造函数。

例如:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script>
            //借用构造函数
            function Person(name,age,sex){
                this.name = name;
                this.age = age;
                this.sex = sex;
            }
            //子类型
            function Student(name,age,sex,score){
                Person.call(this,name,age,sex);  //this 为学生对象
                this.score = score;
            }
            
            var student = new Student('zs',18,'男',100);
            console.dir(student)
        </script>
    </body>
</html>

(三)组合继承

组合继承,指的是将原型链和借用构造函数的技术组合到一起。思路是使用原型链实现对原型方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数的复用,又能够保证每个实例都有它自己的属性。

例如:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script>
            //组合继承:借用构造函数 +原型继承
            function Person(name,age,sex){
                this.name = name;
                this.age = age;
                this.sex = sex;
            }
            Person.prototype.sayHi = function(){
                console.log(this.name);
            }
            function Student(name,age,sex,score){
                //借用构造函数,继承属性
                Person.call(this,name,age,sex);  //this 为学生对象
                
                this.score = score;
            }
            //原型继承,继承方法
            Student.prototype = new Person();
            Student.prototype.constructor = Student;
            
            
            var student = new Student('zs',18,'男',100);
            console.dir(student)
        </script>
    </body>
</html>

组合继承避免了原型链和借用构造函数的缺点,融合了他们的优点,是JavaScript中最常用的继承模式。

(四)继承的原型图

通过画图的形式,可以更直观的了解到继承的原理

特此声明:如需转载请注明出处,如有疑问请及时提出以便于改正,如有侵权,联系删除,谢谢
原文地址:https://www.cnblogs.com/CGWTQ/p/10426227.html