标签:javascript模拟实现继承 继承一次父类模板和原型对象
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘oop7.jsp‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
//实现只继承父类的原型对象
function extend(Sub,Sup){
//1.用一个空函数进行中转
//穿件一个空函数,目的:中转
var F=new Function();
F.prototype=Sup.prototype; //实现空函数的原型对象和超类的原型对象转换
Sub.prototype=new F(); //原型继承
Sub.prototype.constructor=Sub; //还原子类的构造器
//保存父类的原型对象 1.方便解耦 2.可以方便获得分类的原型对象
Sub.superClass=Sup.prototype; //自定义一个子类的静态属性,接收父类的原型对象
if(Sup.prototype.constructor==Object.prototype.constructor){
Sup.prototype.constructor=Sup; //手动还原父类原型对象的构造器
}
}
//混合继承:原型继承+构造函数继承
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype={
constructor:Person,
sayName:function(){
alert(this.name);
}
}
function Boy(name,age,sex){
Boy.superClass.constructor.call(this,name,age); //绑定父类的模板函数,借用构造,支复制了父类的模板
this.sex=sex;
}
//Boy.prototype=new Person(); //既继承了父类的模板,又继承了父类的原型,但由于不习惯于在new Person时传入参数,所以会再使用call函数继承模板
extend(Boy,Person);
//给子类加上一个父类的覆盖方法
Boy.prototype.sayName=function(){
alert(‘子类复写方法‘);
}
var b=new Boy(‘张三‘,23,‘男‘);
alert(b.sex);
b.sayName();
Boy.superClass.sayName.call(b); //调用父类的同名函数
//3件事
//混合继承缺点:继承了两次父类的模板,一次父类的原型对象
//2集成一次父类的模板,一次父类的原型对象
//只继承一遍父类的模板 自定义方法实现只继承一遍父类的模板extend方法
</script>
</head>
<body>
This is my JSP page. <br>
</body>
</html>本文出自 “matengbing” 博客,请务必保留此出处http://matengbing.blog.51cto.com/11395502/1879664
javascript模拟实现继承,继承一次父类模板和原型对象
标签:javascript模拟实现继承 继承一次父类模板和原型对象
原文地址:http://matengbing.blog.51cto.com/11395502/1879664