国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 13:12:33
字體:
來源:轉載
供稿:網友

本文實例講述了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);

使用在線HTML/CSS/JavaScript代碼運行工具 http://tools.VeVB.COm/code/HtmlJsRun,運行結果如下:

多態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);

使用在線HTML/CSS/JavaScript代碼運行工具 http://tools.VeVB.COm/code/HtmlJsRun,運行結果如下:

更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 来安县| 麻江县| 乌海市| 昭平县| 岳西县| 阳城县| 西华县| 马关县| 滨海县| 峨眉山市| 阳原县| 华宁县| 固阳县| 桃源县| 会同县| 资兴市| 芒康县| 阳春市| 贵州省| 曲阳县| 彭州市| 云浮市| 萍乡市| 滨州市| 新营市| 武胜县| 南皮县| 临沭县| 盐源县| 大连市| 濉溪县| 庆云县| 星子县| 泽普县| 运城市| 桦甸市| 清原| 施甸县| 广东省| 海口市| 北海市|