您的位置:首页 > Web前端 > JavaScript

javascript类式继承模式#2——借用构造函数

2013-11-21 09:16 169 查看
<!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>类式继承模式#2——借用构造函数</title>
</head>

<body>
<script type="text/javascript">

function Article(){
this.tags=['js','ajax'];
};

Article.prototype.say=function(){return this.tags;}

/***************************************/
var article=new Article();

function BlogPost(){};

BlogPost.prototype=article;
BlogPost.prototype.say=111;

var blog=new BlogPost();

function StaticPage(){
Article.call(this);
};
StaticPage.prototype={
x:100,
y:function(){
return this.x;
}
}

var page = new StaticPage();

//BlogPost的原型继承了new Article(),即使在BlogPost.prototype上添加属性方法,事实上还是给Article构造函数添加属性方法
console.log(blog);

//将父类Article中的方法属性继承过来,其实就是拷贝过来,占为己有,并且可以覆盖父类中的属性方法,但并没有将父类的原型链拷贝过来;
console.log(page);

//构造函数模式缺点:调用父构造函数的原型,子构造函数能获取到父构造函数的属性和方法,但却未继承父构造函数的原型,即父构造函数__proto__所保存的链接没有继承给子构造函数。

//构造函数模式优点:可以复制父构造函数的属性和方法,并不会出现子构造函数覆盖父构造函数的意外风险,能实现多重继承,可以父子构造函数之间传递参数。

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐