---
title: "JavaScript简单类继承示例"
author: "tobylxy"
date: "2012-12-14T17:02:12Z"
tags: []
categories: ["编程语言"]
slug: "javascript"
draft: false
lastmod: "2012-12-14T17:02:12Z"
id: 1748154
url: "https://tobylxy.iteye.com/blog/1748154"
---

```java

/*
  首先给Object类添加继承方法extends, 
  前两句起继承父类的作用，使得调用的子类能够获得父类的所有属性和方法 
  后一句保存对一个对父类的引用，以便在需要的时候可以调用父类的方法 
*/ 
Object.prototype.extend = function(SuperClass){
	this.SuperClass = SuperClass;
	this.SuperClass();
	this.parent = new SuperClass(); // 如果不需要使用父类的方法，最后一句可以删除
}

function Parent(){
	this.show = function(){
		alert("Parent show()");
	}	
	this.override = function(){
		alert("Parent override()");
	}
}

function Child(){
	this.extend(Parent);
	this.override = function(){
		alert("Child override()");
	}
}

// test
var c = new Child();
c.show();
c.override();
c.parent.override(); // Parent.override()

```