對JavaScript面對對象#繼承的理解

來源:互聯網
上載者:User

前期看到一篇高手寫的文章<悟透JavaScript>,文章非常棒,讀了好幾遍。

記下自己對JavaScript#OOP這塊的感悟,其實重要的點就兩個,一個是結構,一個是資料,如果還有第三個那就應該是規則定義或約束。

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>對OO的感悟</title><script type="text/javascript" language="JavaScript1.5">/** * 考慮JavaScript構造繼承體系,是否可依據用途定義出兩種對象 * <p>1、結構對象,負責描述具體資料對象的結構,類似Java中的類 * <p>2、資料對象,是JavaScript對象,包含結構對象定義的結構,包含獨立的資料,類似Java中的類執行個體 *///根對象var OBJECT = {isA:function(e) {var currType = this;while (currType) {if (currType == e.P_TYPE) {return true;}currType = currType.P_TYPE;}return false;}};/** * 構造類繼承體系 * <p>實現原理: * <p>1、利用prototype原型鏈綁定父類結構對象,使得子類繼承了父類結構</p> * <p>2、增加P_TYPE標識用於標識當前對象父類</p> * <p>3、為最終子類結構對象複製屬性</p> * </p> * <p>基礎知識: * <p>1、需要理解var tmpObj = new FunctionName(){}的意義</p> * <p>1.1、new Object();</p> * <p>1.2、FunctionName.apply(this),建構函式的責任是用來搞初始化的</p> * <p>1.3、tmpObj = this = 1.1構造的new Object()</p> * <p>2、prototype,JavaScript只有對象繼承鏈,沒有類繼承鏈</p> * </p> * @param baseClass 基類結構對象 * @param newClass 臨時子類結構對象 * @return 最終子類結構對象 */function CLASS(baseClass, newClass) {function _innerFunc() {this.P_TYPE = baseClass;for (var member in newClass) {this[member] = newClass[member];}}_innerFunc.prototype = baseClass;return new _innerFunc();}/** * 依據結構物件建構資料對象 * <p>實現原理: * <p>1、定義執行個體 對象初始化責任(需要有CREATE方法)</p> * <p>2、注意原型鏈搜尋路徑,加入了對象結構對象</p> * </p> */function NEW(obj, param) {function _innerFunc() {if (obj.CREATE) {obj.CREATE.apply(this, param);}}_innerFunc.prototype=obj;return new _innerFunc();}function doTest() {//類結構對象var Person = CLASS(OBJECT, {CREATE:function(name, age) {this.name = name;this.age = age;},sayHello:function() {console.log(this.name + ":" + this.age);}});var Employee = CLASS(Person, {CREATE:function(name, age,salary) {this.P_TYPE.CREATE(name, age);//super(name,age)this.salary = salary;},showSalary:function() {console.log(this.name + ":" + this.age + ":" + this.salary);}});//類資料對象var person = NEW(Person, ['小C', '20']);person.sayHello();var employee = NEW(Employee, ['小D', '20', '$200']);employee.showSalary();}</script></head><body><input type="button" value="doTest" onclick="doTest();"/></body></html>

相關文章

聯繫我們

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