复制代码 代码如下:
var JsObject = {} || new Object();
JsObject.extend = function(subClass, superClass){
//先判断子类subClass是否已经定义,如果未定义,则重新定义类。
if(typeof subClass == "undefined")subClass = function(){};
//如果父类superClass是类,则转化成对象
if(typeof superClass == "function")superClass = new superClass();
//遍历父类superClass对象中的属性和方法
for(var p in superClass)
{
/*将父类superClass对象中的属性和方法复制到子类prototype对象中,
因此子类拥有父类的所有特性,即为继承 */
subClass.prototype[p] = superClass[p];
}
return subClass;
};
function Student()
{
this.name = "张三";
this.updateName = function(name){
this.name = name;
}
}
function Class1()
{
this.sex = "男";
this.updateSex = function(sex){
this.sex = sex;
}
}
//定义类Class1继承Student类
Class1 = JsObject.extend(Class1, Student);
var obj = new Class1();
alert(obj.sex);
alert(obj.name);
obj.updateSex("女");
obj.updateName("玛丽");
alert(obj.sex);
alert(obj.name);
结果显示:男,张三,女,玛丽