JavaScript實現多態和繼承的封裝操做示例

封裝Encapsulation前端

以下代碼,這就算是封裝了windows

(function (windows, undefined) {
  var i = 0;//相對外部環境來講,這裏的i就算是封裝了
})(window, undefined);

繼承Inheritance函數

(function (windows, undefined) {
  //父類
  function Person() { }
  Person.prototype.name = "name in Person";
  //子類
  function Student() { }
  Student.prototype = new Person();      //修復原型
  Student.prototype.constructor = Student;  //構造函數
  Student.prototype.supr = Person.prototype; //父類
  //建立子類實例
  var stu = new Student();
  Student.prototype.age = 28;
  Student.prototype.name = "name in Student instance";
  //打印子類成員及父類成員
  console.log(stu.name); //name in Student instance
  console.log(stu.supr.name); //name in Person
  console.log(stu.age); //28
})(window, undefined);

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力學習

運行結果以下: 多態Polymorphismprototype

有了繼承,多態就好辦了code

//這就是繼承了
(function (windows, undefined) {
  //父類
  function Person() { }
  Person.prototype.name = "name in Person";
  Person.prototype.learning = function () {
    console.log("learning in Person")
  }
  //子類
  function Student() { }
  Student.prototype = new Person();      //修復原型
  Student.prototype.constructor = Student;  //構造函數
  Student.prototype.supr = Person.prototype; //父類
  Student.prototype.learning = function () {
    console.log("learning in Student");
  }
  //工人
  function Worker() { }
  Worker.prototype = new Person();      //修復原型
  Worker.prototype.constructor = Worker;  //構造函數
  Worker.prototype.supr = Person.prototype; //父類
  Worker.prototype.learning = function () {
    console.log("learning in Worker");
  }
  //工廠
  var personFactory = function (type) {
    switch (type) {
      case "Worker":
        return new Worker();
        break;
      case "Student":
        return new Student();
        break;
    }
    return new Person();
  }
  //客戶端
  var person = personFactory("Student");
  person.learning(); //learning in Student
  person = personFactory("Worker");
  person.learning(); //learning in Worker
})(window, undefined);

運行結果以下: blog

相關文章
相關標籤/搜索