原型链的两种继承方式及区别

来源:互联网 发布:facebook软件 编辑:程序博客网 时间:2024/04/29 16:32
<!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>
0 0
原创粉丝点击