原型链继承

原型链继承的原理: 子类的原型对象指向父类的实例

  语法格式:

    子类函数名.prototype = new 父类函数名()

代码示例:

<script>
    //设置父类
    function  Father(name,age){
        //实例属性
        this.name = name;
        this.age = age;
        this.tel = 13346542313;
        //实例方法
        this.dance = function(){
            console.log("dancing");
        }
    }
    //原型方法
    Father.prototype.sing = function(){
        console.log("song");
    }
    //设置子类
    function Son(){};
    //利用原型链继承
    Son.prototype = new Father("花花",8);
    //重新定义一个对象,用这个对象来调用子类继承父类的方法或者属性
    var son = new Son();
    son.sing();
</script>

注:如果父类的属性值不固定,原型链继承无法直接改变子类的数据,需要通过构造函数继承和原型链继承结合使用,来解决问题.

原文地址:https://www.cnblogs.com/self-hard/p/10367357.html