JavaScript繼承的實現

來源:互聯網
上載者:User

標籤:.net   setname   ati   tty   person   prototype   pre   使用   rac   

JavaScript繼承有建構函式繼承、原型繼承、複製繼承、建構函式/原型組合繼承等方法,這些繼承方法各有特點。眼下最經常使用的就是建構函式/原型組合繼承。

/** * 實現繼承 * @param  subType    {Function}  子類建構函式 * @param  superType  {Function}  父類建構函式 */function inherit(subType, superType){    function F(){}    F.prototype = superType.prototype;    var p = new F();    p.constructor = subType;    subType.prototype = p;}/** * 父類 * @param  name  {String}  姓名 * @param  age   {Number}  年齡 */function Person(name, age){    this.name = name;    this.age = age;}Person.prototype.getName = function(){    return this.name;};Person.prototype.setName = function(name){    this.name = name;};Person.prototype.getAge = function(){    return this.age;};Person.prototype.setAge = function(age){    this.age = age;};/** * 子類 * @param  name       {String}  姓名 * @param  age        {Number}  年齡 * @param  education  {String}  教育程度 */function Student(name, age, education){    this.education = education;    //調用父類建構函式    Person.call(this, name, age);}//實現繼承//一定要在聲明子類原型方法之前,否則會被覆蓋。

inherit(Student, Person);Student.prototype.setEducation = function(education){ this.education = education;};Student.prototype.getEducation = function(){ return this.education;};var person = new Person(‘小明‘, 25);var student = new Student(‘小剛‘, 22, ‘本科‘);person instanceof Person; //truestudent instanceof Person; //truestudent instanceof Student; //true

父類屬性及方法

子類屬性及方法

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.