javascript繼承(八)-封裝

來源:互聯網
上載者:User

這個系列主要探討的是javascript物件導向的編程,前面已經著重介紹了一下js的繼承,下面想簡單的說一下js如何?封裝的特性。 我們知道物件導向的語言實現封裝是把成員變數和方法用一個類包圍起來,對類中變數的訪問只能通過已定義的介面。封裝可以算是一種資訊隱藏技術,java通過private修飾符將成員變數私人化,並提供對外修改的介面,以控制類中的成員變數的訪問和修改。當然在這些方法中可以對資料進行一些加工。 在前面文章已經介紹了js的屬性問題,那麼在js中如何?對類的屬性隱藏呢?這裡封裝有會有什麼蔽端。 下面看一下實現封裝的代碼: 複製代碼var Person = (function(){    //定義私人方法,相當於private方法,只能在內部訪問    function hello(){        alert('hello world!');    }    return function(){        //定義私人屬性,相當於private屬性,只能在公有方法內部訪問        var name,age;        //定義公有方法,相當於public方法,可以在類的執行個體中方法        this.getName = function(){            return name;        };        this.setName = function(newName){            name = newName;        };        this.getAge = function(){            return age;        }        this.setAge = function(newAge){            age = newAge;        };        this.say = hello;        this.introduce = function(){            alert('my name is :'+this.getName());        }    }})() var p = new Person();p.say(); //hello worldp.setName('xiaoming');p.introduce(); //my name is : xiaoming複製代碼封裝的好處這兒就不用多說了,但在js裡使用一定得注意,避免過度封裝。下面看一下封裝對繼承有沒有什麼影響。 代碼如下: 複製代碼var Person = (function(){    //定義私人方法    function hello(){        alert('hello world!');    }    return function(){        //定義私人屬性,相當於private屬性        var name,age;        //定義公有方法,相當於public方法        this.getName = function(){            return name;        };        this.setName = function(newName){            name = newName;        };        this.getAge = function(){            return age;        }        this.setAge = function(newAge){            age = newAge;        };        this.say = hello;        this.introduce = function(){            alert('my name is :'+this.getName());        }    }})() Person.prototype.call = function(){    this.say();} var Student = function(){    Person.call(this);}for(var i in Person.prototype){Student.prototype[i] = Person.prototype[i]} var s = new Student();s.setName('xiaoli');s.getName();//xiaolis.call();//helloworld複製代碼可以看到Student類繼承了Person類,獲得了Person類的公有方法和共有方法即prototype定義的方法。由於JavaScript並不原生支援封裝,所以在JavaScript中實現封裝一定要注意複雜性的問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.