ITeye博客

JavaScript简单类继承示例

tobylxy · 2012-12-14 17:02 · JavaScript · 编程语言 · Markdown


/*
  首先给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()

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。