ASP.NET AJAX的面向对象思想--访问修饰与继承

来源:互联网 发布:网络举报 编辑:程序博客网 时间:2024/05/19 13:44
继承是一个类派生于另一个类的能力。派生类自动继承基类的所有字段、属性、方法和事件。派生类可以增加新的成员或者重写基类已存在的成员来改变成员的行为。

  下面的脚本实例有两个类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);

    Inheritance.js脚本文件中定义了两个类:Person和Employee,Employee是从Person继承而来。每个类都有字段、公共属性和方法。另外,Employee类重写了toString的实现,并在重写的代码中调用了基类的功能。在这个例子中把类Person的名字空间设定为"Demo"。运行页面Inheritance.aspx,点击“创建对象”、“对象释放”、“公共和私有属性”、“对象方法”、“重写方法”,“对象类型检查”体验一下。