javascipt 实现继承
2015-06-17 17:04
295 查看
//使用 call /apply实现继承,此方法针对父类中所有方法都不是以原型的方式实现的 function person(name,age){ this.name=name; this.age=age; this.show = function(){ console.log("call person name:"+this.name+" age:"+this.age); } } function student(name,age,grade){ person.call(this,name,age); this.grade = grade; } student.prototype.showGrade = function(){ console.log("student call: grade:"+this.grade); }; var stu = new student("zjw",24,1); stu.show(); stu.showGrade();
//使用对象冒充实现继承 function person(name,age){ this.name=name; this.age=age; this.show = function(){ console.log("call person name:"+this.name+" age:"+this.age); } } function student(name,age,grade){ this.person=person; this.person(name,age); delete this.person; this.grade=grade; this.showGrade = function(){ console.log("student call: grade:"+this.grade); } } var stu = new student("zjw",24,1); stu.show(); stu.showGrade();
//使用原型拷贝实现继承,这是最好的方式 function person(name,age){ this.name=name; this.age = age; this.show1 = function(){ console.log("person show1 call: name:"+this.name+" age:"+this.age); } } person.prototype.show2 = function(){ console.log("person show2 call: name:"+this.name+" age:"+this.age); }; function student(name,age,grade){ person.call(this,name,age);//拷贝name age show1 var prop; //复制父类的以原型实现的方法 for (prop in person.prototype) { var proto = this.constructor.prototype; if (!proto[prop]) { proto[prop] = person.prototype[prop]; } proto[prop]["super"] = person.prototype; } this.grade=grade; } student.prototype.show = function(){ console.log("student show call: name:"+this.name+" age:"+this.age+" grade:"+this.grade); }; var stu = new student("zjw",24,1); stu.show1(); stu.show2(); stu.show();
方法4:
function person(name,age,obj){ console.log("person call"+arguments.length); this.name = name; this.age = age; this.obj = obj; this.method1 = function(){ console.log("method1 call:"+this.name+"--"+this.age+"---"+this.obj); } } person.prototype.method2 = function(){ console.log("method2 call:"+this.name+"---"+this.age+"---"+this.obj); }; function student(name,age,grade,obj){ person.call(this,name,age,obj); } function inherits(curClass,parentClass){ curClass.prototype = new parentClass(); } inherits(student,person); var stu1 = new student("zjw",24,1,[1,2,3]); stu1.method1(); stu1.method2();
相关文章推荐
- Spring学习笔记之 Spring IOC容器(二)
- eclipse设置和优化
- spring+springMVC+Mybatis+dwz 开发
- Java上的try catch并不影响性能
- pharmdock并行运算的java实现
- Java并发编程-19-在执行器中延时执行任务和周期性执行任务
- java定义和实现接口
- 我的Java开发学习之旅------>System.nanoTime与System.currentTimeMillis的区别
- 在Eclipse在使用JUnit4单元测试(0基础知识)
- java.lang.outofmemoryerror:permgen space jvm内存溢出解决办法
- java 正则表达式例子, 查找字符串
- java.lang.OutOfMemoryError: Java heap space解决方法
- java之二叉树和为某一值的路径
- java时间戳
- java时间戳
- java中Pattern.compile函数的相关解释
- Java最著名的开源项目
- 【failed to create java virtual machine】 解决方案
- 关于java.lang.UnsatisfiedLinkError的小案例
- eclipse 中文乱码问题解决