剖析ASP.NET AJAX的面向对象思想(2)
2.访问修饰
许多面向对象编程语言都有访问修饰的概念。允许你指定类或成员在某种范围内有效。例如可在外部执行的程序、具有相同名字空间的内部类或特指的代码快内的类等。在JavaScript中没有访问修饰,但在ASP.NET AJAX中约定以下划线字符开头"_"的被认为是私有的,类的外部不能访问。
3.继承
继承是一个类派生于另一个类的能力。派生类自动继承基类的所有字段、属性、方法和事件。派生类可以增加新的成员或者重写基类已存在的成员来改变成员的行为。
下面的脚本实例有两个类Person和Employee,Employee从Person继承而来,两个类示范了私有字段的使用,它们都有公共属性、方法。另外Employee类重写了Person类的toString实现,并调用了基类的功能。
Type.registerNamespace("Demo");
Demo.Person = function(firstName, lastName, emailAddress) { this._firstName = firstName; this._lastName = lastName; this._emailAddress = emailAddress; } Demo.Person.prototype = { getFirstName: function() { return this._firstName; }, getLastName: function() { return this._lastName; }, getEmailAddress: function() { return this._emailAddress; }, setEmailAddress: function(emailAddress) { this._emailAddress = emailAddress; }, getName: function() { return this._firstName + ' ' + this._lastName; }, dispose: function() { alert('bye ' + this.getName()); }, sendMail: function() { var emailAddress = this.getEmailAddress(); if (emailAddress.indexOf('@') < 0) { emailAddress = emailAddress + '@example.com'; } alert('Sending mail to ' + emailAddress + ' ...'); }, toString: function() { return this.getName() + ' (' + this.getEmailAddress() + ')'; } } Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable); Demo.Employee = function(firstName, lastName, emailAddress, team, title) { Demo.Employee.initializeBase(this, [firstName, lastName, emailAddress]); this._team = team; this._title = title; } Demo.Employee.prototype = { getTeam: function() { return this._team; }, setTeam: function(team) { this._team = team; }, getTitle: function() { return this._title; }, setTitle: function(title) { this._title = title; }, toString: function() { return Demo.Employee.callBaseMethod(this, 'toString') + '\r\n' + this.getTitle() + '\r\n' + this.getTeam(); } } Demo.Employee.registerClass('Demo.Employee', Demo.Person); |