JS 类继承 原型继承

参考文档: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);

有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


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