子对象的属性和方法,继承可以提高代码的复用性

   就是子对象自动拥有父对象的属性和方法,继承可以提高代码的复用性。 JS里的继承主要依靠是的原型链。让原型对象(每一个构造函数都有一个原型对象)的值js 原型链,等于另一个类型实例,即实现了继承;另外一个类型的原型再指向第三个类型的实例,以此类推,也就形成了一个原型链

   function Animal(newName,newAge){

            this.name = newName;
            this.age = newAge;
        }
        Animal.prototype.eat = function(str){
            console.log(this.name + "吃" + str);
        }
        function Person(newId){
            this.id = newId;
        }
        Person.prototype = new Animal("老王",18);
        let p1 = new Person("007");
        console.log(p1.name,p1.age,p1.id);
        p1.name = "小明";
        p1.eat("米饭");
        let p2 = new Person("008");
        console.log(p2.name,p2.age,p2.id);
        p1.name = "大明";
        p1.eat("水果");

   console.log(p1 instanceof Person);

        console.log(p2 instanceof Person);

  原型链继承

  让子对象的原型指向父对象的实例,父对象的原型指向爷爷对象的实例js 原型链,依次类推,就形成了原型链

   function Animal(newAge){

            this.age = newAge;
        }
        Animal.prototype.eat = function(){
            console.log("Animal.eat");
        }
        function Person(newId){
            this.id = newId;
        }
        Person.prototype = new Animal(18);
        Person.prototype.study = function(){
            console.log("Person.study");
        }
        function Pupli(newTall){
            this.tall = newTall;
        }
        Pupli.prototype = new Person("007");
        Pupli.prototype.play = function(){
            console.log("Pupli.play");
        }
        
        let pu = new Pupli(140);
        console.log(pu.age,pu.id,pu.tall);
        pu.eat();
        pu.study();
        pu.play();

  注意事项: 1. 先定义原型继承关系,再添加子类的自定义方法或属性(原型的属性,即共享的属性和方法要在原型继承关系确立后,再定义)。 2. 利用原型链继承,给子类添加原型方法时,不可以重写prototype

   function Animal(newAge){

            this.age = newAge;
        }
        function Person(newId){
            this.id = newId;
        }
        Person.prototype.eat = function(){
            console.log("Person eat");
        }
        Person.prototype = new Animal(15);
        
        let p = new Person("007");
        console.log(p.id);
        p.eat();

  缺点: 1. 被继承的类型(父类)里包括引用类型的属性的时候,它会被所有实例共享其值 2. 创建子类型的实例时,没法传参给被继承类型。

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1817
0 评论
348

发表评论

!