`
v5qqbrowser
  • 浏览: 356529 次
文章分类
社区版块
存档分类
最新评论

javascript 类的继承3

 
阅读更多
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>
<!---
简化类的声明,把派生子类的整个过程包装在extend函数中
-->
 <body>
	<script>

		//更加通用化,不用固化超类的名称
		function extend2(subClass, superClass) {
			var F = function() {};
			F.prototype = superClass.prototype;
			subClass.prototype = new F();
			subClass.prototype.constructor = subClass;
			
			//增加一个superClass属性
			subClass.superClass = superClass.prototype;
			if(superClass.prototype.constructor == Object.prototype.constructor) {
				superClass.prototype.constructor = superClass;//构造函数名
			}
		}


		function Person(name) {
			this.name = name;
		}

		Person.prototype.getName = function() {
			return this.name;
		}

		function Author(name, books) {
			Author.superClass.constructor.call(this,name);//call the superclass's constructor
			this.books = books;
		}

		extend2(Author,Person);

		Author.prototype.getBooks = function() {
			return this.books;
		}

		var author = new Author('Dustin Diaz',['javascript design patterns ']);
		alert(author.getName());
		alert(author.getBooks());

	</script>
 </body>
</html>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics