0

我的问题是我不明白为什么这个覆盖在这里不起作用是源

window.onload=function()
{
   function Person(first,last)
   {
      this.First=first;
      this.Last = last;
      this.Full=function()
      {
         return this.First+" "+this.Last;
      };
   }

   Person.prototype.GetFullName=function()
   {
      return this.First + " " + this.Last;
   } ;



   function Employee(first,last,position)
   {
      Person.call(this,first,last);
      this.Position=position;
   }
   /* Employee.prototype = new Person();
   var t = new Employee("Mohamed","Zaki","Web Developer");

   alert(t.GetFullName());
    */
   Employee.prototype.GetFullName=function()
   {
      var x = Person.prototype.GetFullName.call(this);
      return x + " , " + this.Position ; 
   }
   var e = new Employee("Mohamed","Zaki","Web Developer");
   alert(e.GetFullName());
   }
4

2 回答 2

1

如果我理解您的问题,您注释掉的代码不起作用,因为它是在覆盖 GetFullName 之前执行的。

/* 
   **** this code is executed before GetFullName is overridden and will use
   **** original function 
   Employee.prototype = new Person();
   var t = new Employee("Mohamed","Zaki","Web Developer");

   alert(t.GetFullName());
    */

   Employee.prototype.GetFullName=function()
   {
      var x = Person.prototype.GetFullName.call(this);
      return x + " , " + this.Position ; 
   }

   /**** This code is executed after GetFullName is overridden uses the new version */
   var e = new Employee("Mohamed","Zaki","Web Developer");
   alert(e.GetFullName());
   }
于 2012-04-13T04:40:19.633 回答
1

首先,删除 window.onload 包装器,因为它没有做任何有用的事情。解释如下:

  function Person(first,last) { 
    this.First = first; 
    this.Last = last; 
    this.Full = function() { 
      return this.First + " " + this.Last; 
    }; 
  } 

  Person.prototype.GetFullName = function() {  
    return this.First + " " + this.Last; 
  } ; 

  function Employee(first,last,position) { 
    Person.call(this,first,last); 
    this.Position = position; 
  } 
  Employee.prototype = new Person(); 

  var t = new Employee("Mohamed","Zaki","Web Developer"); 

  // Here getFullName is called before the new method is added
  // to Person.prototype so you only get first and last name
  alert(t.GetFullName()); 

  // Here is where the new method is added
  Employee.prototype.GetFullName=function() { 
    var x = Person.prototype.GetFullName.call(this); 
    return x + " , " + this.Position ; 
  }

  var e = new Employee("Mohamed","Zaki","Web Developer"); 

  // so here you get first, last and position
  alert(e.GetFullName()); 

  // And existing instances get the new method too
  alert(t.GetFullName()); 
于 2012-04-13T04:43:34.233 回答