原型链的两种继承方式及区别
2017-02-10 17:59
274 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script>
//创建父类构造器
function parent(){
this.x=1;
}
parent.prototype.y=2; //父类构造器原型
parent.prototype.add = function (x, y) { //为父类构造器原型添加方法
return x + y;
}
//--------------------------------------------------
//创建子类构造器
function child1(){
this.c1=1;
}
//通过Object.create(parent.prototype)进行原型链的继承只能在父类原型上查找,找不到其父类本身的非原型的属性方法
child1.prototype=Object.create(parent.prototype); //子类构造器原型为一个空对象,其原型指向自父类原型
//进行子类实例的业务操作
var c1=new child1();
console.log("c:"+c1.c1);
console.log("y:"+c1.y);
console.log("x:"+c1.x); //undefined。
//------------------------------------------------
//创建子类构造器
function child2(){
this.c2=1;
}
//通new parent()实例进行原型链的继承 不仅能在父类原型上查找,也能查找在父类本身的非原型的属性方法
var p=new parent();
child2.prototype=p; //子类构造器原型为一个父类的实例
//进行子类实例的业务操作
var c2=new child2();
console.log("c:"+c2.c2);
console.log("y:"+c2.y);
console.log("x:"+c2.x); //value:1
var totle=c2.add(3,5); //执行父类原型上的方法
console.log(totle);
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script>
//创建父类构造器
function parent(){
this.x=1;
}
parent.prototype.y=2; //父类构造器原型
parent.prototype.add = function (x, y) { //为父类构造器原型添加方法
return x + y;
}
//--------------------------------------------------
//创建子类构造器
function child1(){
this.c1=1;
}
//通过Object.create(parent.prototype)进行原型链的继承只能在父类原型上查找,找不到其父类本身的非原型的属性方法
child1.prototype=Object.create(parent.prototype); //子类构造器原型为一个空对象,其原型指向自父类原型
//进行子类实例的业务操作
var c1=new child1();
console.log("c:"+c1.c1);
console.log("y:"+c1.y);
console.log("x:"+c1.x); //undefined。
//------------------------------------------------
//创建子类构造器
function child2(){
this.c2=1;
}
//通new parent()实例进行原型链的继承 不仅能在父类原型上查找,也能查找在父类本身的非原型的属性方法
var p=new parent();
child2.prototype=p; //子类构造器原型为一个父类的实例
//进行子类实例的业务操作
var c2=new child2();
console.log("c:"+c2.c2);
console.log("y:"+c2.y);
console.log("x:"+c2.x); //value:1
var totle=c2.add(3,5); //执行父类原型上的方法
console.log(totle);
</script>
</body>
</html>
相关文章推荐
- js两种定义函数、继承方式及区别
- js两种定义函数、继承方式及区别
- 谈谈VC++中两种函数调用方式的区别
- ADO 与ADO.NET两种数据访问方式区别
- Http协议中,主要常见的传送数据到服务器有哪两种方式,这两种方式的特点和区别,以及其在Http协议中的位置
- 浅谈类两种继承机制--接口(Interface)和类(Class)的区别
- 浅谈类两种继承机制--接口(Interface)和类(Class)的区别
- Apache 两种虚拟主机方式的区别
- C++继承方式区别
- ADO 与ADO.NET两种数据访问方式区别
- ArcSde的两种连接方式、区别和一些常见安装问题
- c#类的继承方式的区别 不是指单or多继承
- ADO与ADO.NET两种数据访问方式区别
- 浅谈类两种继承机制--接口(Interface)和类(Class)的区别
- 单例模式的两种实现方式及区别
- jsp中两种跳转方式的区别?
- ADO 与ADO.NET两种数据访问方式区别?
- MVC中两种网页跳转方式的比较和区别
- Apache 两种虚拟主机方式的区别
- ADO 与ADO.NET两种数据访问方式区别