JS高級---利用原型共享數據

什麼樣子的數據是須要寫在原型中? 須要共享的數據就能夠寫原型中函數

原型的做用之一: 數據共享學習

 

    //屬性須要共享, 方法也須要共享
    //不須要共享的數據寫在構造函數中,須要共享的數據寫在原型中
    //構造函數
    function Student(name,age,sex) {
      this.name=name;
      this.age=age;
      this.sex=sex;
    }
    //全部學生的身高都是188,全部人的體重都是55
    //全部學生都要天天寫500行代碼
    //全部學生天天都要吃一個10斤的西瓜
    //原型對象
    Student.prototype.height="188";
    Student.prototype.weight="55kg";
    Student.prototype.study=function () {
      console.log("學習,寫500行代碼,小菜一碟");
    };
    Student.prototype.eat=function () {
      console.log("吃一個10斤的西瓜");
    };
    //實例化對象,並初始化
    var stu=new Student("晨光",57,"女");
    console.dir(Student);
    console.dir(stu);
//    stu.eat();
//    stu.study();
相關文章
相關標籤/搜索