我的问题是,我不明白为什么这个覆盖在这里不起作用是源
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());
}
答案 0 :(得分: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());
}
答案 1 :(得分: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());