Posted in Javascript onFebruary 08, 2011
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);
结果显示:男,张三,女,玛丽
Javascript面向对象之四 继承
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@