1. 程式人生 > >JavaScript實現多型和繼承的封裝操作示例

JavaScript實現多型和繼承的封裝操作示例

封裝Encapsulation

如下程式碼,這就算是封裝了

(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經驗年前端開發人員,幫助突破技術瓶頸,提升思維能力

執行結果如下: 多型Polymorphism

有了繼承,多型就好辦了

//這就是繼承了
(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);

執行結果如下: