2009-01-17 [ASP.NET AJAX]如何使用繼承 3103 0 ASP.NET AJAX 摘要:[ASP.NET AJAX]如何使用繼承 ASP.NET AJAX Library 提供JavaScript 實現 OOP 概念本文介紹如何實作 OOP 的繼承一般來說繼承有幾個要注意的地方1.如何實作繼承2.初始化父類別時傳遞參數給父類別建構函式3.覆寫父類別方法4.在衍生類別的方法中呼叫父類別方法(如果衍生類別有與父類別方法同名的話)JS檔/// <reference name="MicrosoftAjax.js" /> // 建立命名空間 Type.registerNamespace("Demo"); // 建立父類別 Demo.Human = function(name, age) { this._name = name; this._age = age; } Demo.Human.prototype = { set_name: function(name) { this._name = name; }, get_name: function() { return this._name; }, set_age: function(age) { this._age = age; }, get_age: function() { return this._age; }, toString: function() { }, clearInfo: function() { this.set_name(""); this.set_age(""); } } // 註冊父類別 Demo.Human.registerClass("Demo.Human"); // 建立衍生類別 Demo.Person = function(name, age, country) { // 初始化父類別,呼叫父類別建構子以 Array 傳入. Demo.Person.initializeBase(this, [name, age]); this._country = country; } Demo.Person.prototype = { set_country: function(country) { this._country = country; }, get_country: function() { return this._country; }, // 覆寫父類別 toString 方法 toString: function() { return "姓名:" + this.get_name() + " , 年齡:" + this.get_age() + " , 國家:" + this.get_country(); }, clearInfo: function() { // 呼叫父類別 clearInfo 方法 Demo.Person.callBaseMethod(this, "clearInfo"); this.set_country(""); ; } } // 註冊衍生類別,繼承父類別 Demo.Person.registerClass("Demo.Person", Demo.Human); if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();Web 畫面Web Scriipt<script src="jquery-1.2.6.js" type="text/javascript"></script> <script type="text/javascript"> function pageLoad() { $("#Button1").click(function() { var people = new Demo.Person("Max", 25, "Taiwan"); var message = people.toString() + "\n\n"; message += "清除資料\n"; people.clearInfo(); message += people.toString(); $("#TextArea1").val(message); }); } </script> ASP.NET AJAX 回首頁