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";
 
    //打印子類成員及父類成員
    alert(stu.name); //name in Student instance
    alert(stu.supr.name); //name in Person
    alert(stu.age); //28
 
})(window, undefined);

 

多態Polymorphism

有了繼承,多態就好辦了

//這就是繼承了
(function (windows, undefined) {
    //父類
    function Person() { }
    Person.prototype.name = "name in Person";
    Person.prototype.learning = function () {
        alert("learning in Person")
    }
 
    //子類
    function Student() { }
    Student.prototype = new Person();           //修復原型
    Student.prototype.constructor = Student;    //構造函數
    Student.prototype.supr = Person.prototype;  //父類
    Student.prototype.learning = function () {
        alert("learning in Student");
    }
 
    //工人
    function Worker() { }
    Worker.prototype = new Person();           //修復原型
    Worker.prototype.constructor = Worker;    //構造函數
    Worker.prototype.supr = Person.prototype;  //父類
    Worker.prototype.learning = function () {
        alert("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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM