码迷,mamicode.com
首页 > Web开发 > 详细

JS 类继承 原型继承

时间:2016-12-12 22:25:09      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:对象   png   nbsp   技术   组合模式   模式   end   调用   方式   

参考文档:JS原型继承和类继承

<script src="jquery-2.0.3.js">


</script>
<script>
/*//类继承 
 var father=function(){
    this.age=53;
    this.say=function(){
        console.log("name:"+this.name+",age:"+this.age);
    }
 };
 var child=function(){
    this.name="child";
    father.call(this);
 }
 var man=new child();
 man.say();
console.log(man);
*/ //原型继承 var father=function(){} father.prototype.a=function(){console.log(11)}; var child=function(){}; child.prototype=new father(); var man=new child(); man.a(); console.log(man); </script>

类继承时打印man:

技术分享

 

原型继承时打印man:

技术分享

 看似,原型继承时,对象可以调用原型上的方法

 

类继承的方法,每一次都会存到内存中,损耗性能,并且不容易扩展

原型继承:很灵活,改变原型链即可,写好extend就可以

 

通常继承会汇聚两种方式的优点,组合模式就是这样做:用类继承去继承属性(每个实例的属性应该是私有的,不应该是共有的),用原型继承去继承方法

例如

  var father=function(){
    this.age=53;
    
 };
 father.prototype.b=new function(){
    console.log(this.age);
 }
 var child=function(){
    
    father.call(this);
 }
child.prototype=new father();
var man=new child();
console.log(man);

技术分享

 **使用 Object.create()

var father ={
    a:‘father‘,
    b:function(){
        console.log(this.a);
    }
}
var obj=Object.create(father);
console.dir(obj);

 

技术分享

 

JS 类继承 原型继承

标签:对象   png   nbsp   技术   组合模式   模式   end   调用   方式   

原文地址:http://www.cnblogs.com/qingmaple/p/6165609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!