1.使用call方法实现

function Person(name)
{
    
this.name=name;
    
this.eat = function(){
        alert(
this.name+" eat up the apple!");
    }
}

function Employee(name,age){
  
this.age = age;
  Person.call(
this,name);
  
this.showAge = function(){
      alert(
this.name+"'s age is "+this.age);
  }
}

var emp = new Employee("kai",22);
emp.eat(
"cc");

输出>>>>>kai eat up the apple!

 但是当我们给Person 加一个prototype方法时,就继承不了了。

Person.prototype.say=function(){
  alert("Hello , I'm "+this.name );
 }

2.只有建一个基类的对象作为子类原型的原型:

function Person(name)
{
    
this.name=name;
    
this.eat = function(){
        alert(
this.name+" eat up the apple!");
    }
}
Person.prototype.say
=function(){
    alert(
"Hello , I'm "+this.name );
}

function Employee(name,age){
  
this.age = age;
  Person.call(
this,name);
  
this.showAge = function(){
      alert(
this.name+"'s age is "+this.age);
  }
}
Employee.prototype 
= new Person();  //建一个基类的对象作为子类原型的原型
var emp = new Employee("kai",22);
emp.say();
输出
>>>>Hello , I'm kai

3.现在把Person.call(this,name);去掉。。

function Person(name)
{
    
this.name=name;
    
this.eat = function(){
        alert(
this.name+" eat up the apple!");
    }
}
Person.prototype.say
=function(){
    alert(
"Hello , I'm "+this.name );
}

function Employee(name,age){
  
this.age = age;
  
this.showAge = function(){
      alert(
this.name+"'s age is "+this.age);
  }
}
Employee.prototype 
= new Person();  //建一个基类的对象作为子类原型的原型
var emp = new Employee("kai",22);
emp.eat(
"cc");
emp.showAge();
输出
>>>>undefined eat up the apple!
输出
>>>>undefined's age is "+this.age

Person.call(this,name); 调用了基类的构造

 posted on 2009-06-30 11:02  将军  阅读(226)  评论(0编辑  收藏  举报