javascript內部原理篇[javascript實現繼承]

來源:互聯網
上載者:User

javascript的物件導向並非新鮮事務,現在簡單類比OOP實現繼承

/** * 繼承 */(function(){    //建立一個人員類    function Person(name){        this.name = name;    }    //建立一個Teacher類    function Teacher(name, books){        //call方法可以讓一個函數的物件內容從初始化變為由this來決定        //調用Person的建構函式,因為Person沒用new 所以是個Null 物件        //相當於java中的super函數        Person.call(this, name);        this.books = books;    }    /**     * 建立extend函數為了所有的繼承操作     */    function extend(subClass, superClass){        //叫子類原型類屬性等於父類原型類屬性        subClass.prototype = new superClass();        subClass.prototype.constructor = subClass;        //為了以後能夠方便調用,也就是說在不知父類名稱的情況下,可以直接調用        //我們增加以下語句        subClass.superClass = superClass.prototype;    }    function Author(name,books){        //Author.superClass.constructor.call(this,name);        //繼承,將name屬性的賦值方式在本類中繼承        Author.superClass.constructor.call(this,name);        //Person.call(this,name);        this.books = books;        this.getBook = function(){            return this.name +" "+ this.books;        }    }    extend(Author, Person);    var peter = new Author("123","JAVASCIPT");    alert(peter.getBook())})();


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.