js面向对象编程,一个完整原形的继承例子

js面向对象编程,一个完整原型的继承例子



/* 基类*/

var Person = {
  name: 'default name',
  getName: function() {
    return this.name;
  }
};

公共方法

function clone(object) {
    function F() {}
    F.prototype = object;
    return new F;
}

/* 子类1*/
var reader = clone(Person);
alert(reader.getName()); // This will output 'default name'.
reader.name = 'John Smith';
alert(reader.getName()); // This will now output 'John Smith'.

/* 子类1*/

var Author = clone(Person);
Author.books = []; // Default value.
Author.getBooks = function() {
  return this.books;
}

var author = [];
/* 定义实例*/
author[0] = clone(Author);
author[0].name = 'Dustin Diaz';
author[0].books = ['JavaScript Design Patterns'];

author[1] = clone(Author);
author[1].name = 'Ross Harmes';
author[1].books = ['JavaScript Design Patterns'];

author[1].getName();
author[1].getBooks();