繼承 屬性和方法

//爲了數據共享,改變原型指向,做到了繼承---通過改變原型指向實現的繼承

//缺陷:因爲改變原型指向的同時實現繼承,直接初始化了屬性,繼承過來的屬性的值都是一樣的了,所以,這就是問題
//只能重新調用對象的屬性進行重新賦值,
//解決方案:繼承的時候,不用改變原型的指向,直接調用父級的構造函數的方式來爲屬性賦值就可以了------借用構造函數:把要繼承的父級的構造函數拿過來,使用一下就可以了
//借用構造函數:構造函數名字.call(當前對象,屬性,屬性,屬性....);
//解決了屬性繼承,並且值不重複的問題
//缺陷:父級類別中的方法不能繼承
function Person(name, age, sex, weight) {
      this.name = name;
      this.age = age;
      this.sex = sex;
      this.weight = weight;
    }
    Person.prototype.sayHi = function () {
      console.log("您好");
    };
    function Student(name,age,sex,weight,score) {
      //借用構造函數
      Person.call(this,name,age,sex,weight);
      this.score = score;
    }
    var stu1 = new Student("小明",10,"男","10kg","100");
    console.log(stu1.name, stu1.age, stu1.sex, stu1.weight, stu1.score);

    var stu2 = new Student("小紅",20,"女","20kg","120");
    console.log(stu2.name, stu2.age, stu2.sex, stu2.weight, stu2.score);

    var stu3 = new Student("小麗",30,"妖","30kg","130");
    console.log(stu3.name, stu3.age, stu3.sex, stu3.weight, stu3.score);

但是這種方法只能繼承屬性 不能繼承方法。

//原型實現繼承
//借用構造函數實現繼承
//組合繼承:原型繼承+借用構造函數繼承
function Person(name,age,sex) {
      this.name=name;
      this.age=age;
      this.sex=sex;
    }
    Person.prototype.sayHi=function () {
      console.log("人");
    };
    function Student(name,age,sex,score) {
      //借用構造函數:屬性值重複的問題
      Person.call(this,name,age,sex);
      this.score=score;
    }
//改變原型指向----繼承
Student.prototype=new Person();//不傳值
    Student.prototype.eat=function () {
      console.log("吃東西");
    };
    var stu=new Student("小黑",20,"男","100分");
    console.log(stu.name,stu.age,stu.sex,stu.score);
    stu.sayHi();
    stu.eat();
    var stu2=new Student("小紅",200,"女","99分");
    console.log(stu2.name,stu2.age,stu2.sex,stu2.score);
    stu2.sayHi();
    stu2.eat();
//屬性和方法都被繼承了

拷貝繼承;把一個對象中的屬性或者方法直接複製到另一個對象中

function Person() {
    }
    Person.prototype.age=10;
    Person.prototype.sex="男";
    Person.prototype.height=100;
    Person.prototype.play=function () {
      console.log("玩的好開心");
    };
    var obj2={};
    //Person的構造中有原型prototype,prototype就是一個對象,那麼裏面,age,sex,height,play都是該對象中的屬性或者方法
    for(var key in Person.prototype){
      obj2[key]=Person.prototype[key];
    }
    console.dir(obj2);
    obj2.play();

//面向對象特性:封裝,繼承,多態

//繼承,類與類之間的關係,面向對象的語言的繼承是爲了多態服務的,
//js不是面向對象的語言,但是可以模擬面向對象.模擬繼承.爲了節省內存空間

//繼承:
/*

  • 原型作用: 數據共享 ,目的是:爲了節省內存空間,
  • 原型作用: 繼承 目的是:爲了節省內存空間
    *
  • 原型繼承:改變原型的指向
  • 借用構造函數繼承:主要解決屬性的問題
  • 組合繼承:原型繼承+借用構造函數繼承
  • 既能解決屬性問題,又能解決方法問題
  • 拷貝繼承:就是把對象中需要共享的屬性或者犯法,直接遍歷的方式複製到另一個對象中
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章