Javascript设计模式系列三

时间:2023-03-09 06:47:58
Javascript设计模式系列三

  继承,一个类或对象继承另一个类或对象的三种方法。类式继承、原型式继承、掺元类。

  一、类式继承,原型链、Extend函数。

 <script type="text/javascript">

        ////定义Person类
var Person = function (name) {
this.name = name;
}; Person.prototype.getName = function () {
return this.name;
}; ////原型链
function Author(name, books) {
Person.call(this, name);
this.books = books;
}; Author.prototype = new Person();
Author.prototype.constructor = Author;
Author.prototype.getBooks = function () {
return this.books;
}; var author = new Author("XX", "books")
alert(author.getName()+author.getBooks()); ////Extend函数
function Extend(subClass,superClass) {
var F = function () { };
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
}; function Author(name, books) {
Person.call(this, name);
this.books = books;
} Extend(Author, Person); Author.prototype.getBooks = function () {
return this.books;
}; var author = new Author("X", "books")
alert(author.getName() + author.getBooks()); </script>

  二、原型式继承。使用原型式继承时,并不需要用类来定义对象的结构,只需直接创建一个对象即可。这个对象随后可以被新的对象重用,该对象被称为原型对象。Clone函数。

 <script type="text/javascript">

        ////Clone函数
function clone(object) {
function F() { };
F.prototype = new object();
return new F();
}; ////定义Person类
var Person = function () {
this.name = 'default name';
this.getName = function () {
return this.name;
}
}; ////实例化
var Author = clone(Person);
alert(Author.name);
Author.name = "原型式继承";
alert(Author.name);
alert(Author.getName()); </script>

  三、掺元类,一个函数用到多个类中,可以使用扩充的方式让这些类共享该函数。

  本文源于:Javascript设计模式。