一条有趣的前端面试题(5)

继承父类的方法

第一种,prototype的方式:

function person(){
    this.eye="big";
    this.hair="black"
    this.view=function(){
        return this.eye+","+this.hair
    }
    
}
 function man(){
 this.feature=["beard","strong"]
}
man.prototype=new person();
var m =new man();
console(m.view());

第二种,apply的方式:

function person(){
    this.eye="big";
    this.hair="black"
    this.view=function(){
        return this.eye+","+this.hair
    }
}
function man(){
  // person.apply(this,new Array()); 
    person.apply(this,[])
    this.feature=["beard","strong"]
}
var one = new man(); 

如果apply参数为空,即没有参数传递,则通过 new Array() 、[] 来传递,null 无效。apply,实现了方法的替换和作对象属性的复制操作

第三种,call+prototype:

function person(){
    this.eye="big";
    this.hair="black"
    this.view=function(){
        return this.eye+","+this.hair
    }
}
function man(){
  // person.call(this,new Array()); 
    person.call(this,[])
    this.feature=["beard","strong"];
}
man.prototype=new person();
var one = new man(); 

call的方式比apply多了man.prototype=new person();是因为call实现了方法的替换但是没有作对象属性的复制操作

备注:带参情况

function Parent(name,age){
    this.name=name;
   this.age=age;
   this.sayHi=function(){
    alert("Hi, my name is "+this.name+", my age is "+this.age);
   }
}
//child 继承parent
 function Child(name,age,grade){
   this.grade=grade;
   Parent.apply(this,[name,age])
   //Parent.call(this,name,age);
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  }
  var chi=new Child("小明","10","5");
  chi.sayHi();
  chi.sayGrade();

第四种,构造函数方法:

function parent(name,age){
    this.name=name;
   this.age=age;
   this.sayHi=function(){
    alert("Hi, my name is "+this.name+", my age is "+this.age);
   }
}
//child 继承parent
 function Child(name,age,grade){
   this.grade=grade;
   this.sayHi=Parent;///////////
   this.sayHi(name,age);
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  }
  var chi=new Child("小明","10","5");
  chi.sayHi();
  chi.sayGrade();
  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,850评论 19 139
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,662评论 0 4
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 12,388评论 2 17
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,499评论 18 399
  • 请参看我github中的wiki,不定期更新。https://github.com/ivonzhang/Front...
    zhangivon阅读 12,159评论 2 19

友情链接更多精彩内容