欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實現(xiàn)多態(tài)和繼承的封裝操作示例

 更新時間:2018年08月20日 11:13:00   作者:kkun  
這篇文章主要介紹了JavaScript實現(xiàn)多態(tài)和繼承的封裝操作,結(jié)合實例形式分析了javascript中多態(tài)與繼承的實現(xiàn)及封裝相關操作技巧,需要的朋友可以參考下

本文實例講述了JavaScript實現(xiàn)多態(tài)和繼承的封裝操作。分享給大家供大家參考,具體如下:

封裝Encapsulation

如下代碼,這就算是封裝了

(function (windows, undefined) {
  var i = 0;//相對外部環(huán)境來說,這里的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;  //構(gòu)造函數(shù)
  Student.prototype.supr = Person.prototype; //父類
  //創(chuàng)建子類實例
  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);

使用在線HTML/CSS/JavaScript代碼運行工具 http://tools.jb51.net/code/HtmlJsRun,運行結(jié)果如下:

多態(tài)Polymorphism

有了繼承,多態(tài)就好辦了

//這就是繼承了
(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;  //構(gòu)造函數(shù)
  Student.prototype.supr = Person.prototype; //父類
  Student.prototype.learning = function () {
    console.log("learning in Student");
  }
  //工人
  function Worker() { }
  Worker.prototype = new Person();      //修復原型
  Worker.prototype.constructor = Worker;  //構(gòu)造函數(shù)
  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);

使用在線HTML/CSS/JavaScript代碼運行工具 http://tools.jb51.net/code/HtmlJsRun,運行結(jié)果如下:

更多關于JavaScript相關內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)

希望本文所述對大家JavaScript程序設計有所幫助。

相關文章

最新評論