一条有趣的前端面试题(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();
  

你可能感兴趣的:(一条有趣的前端面试题(5))