您的位置:首页 > 移动开发 > Objective-C

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

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息