JavaScript 中的覆盖方法
override method in javascript
我在这里的问题是我不明白为什么这个覆盖在这里不起作用是来源
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());
}
如果我理解您的问题,那么您注释掉的代码不起作用,因为它是在 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());
}
首先,删除 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());
相关文章:
- 如何覆盖主干中的extend方法
- 使用通用方法覆盖每个组合getValue字段
- 如何在循环中使用jQuery.on()方法,而不覆盖我循环的对象
- Javascript集:任何覆盖元素之间比较的方法
- 覆盖 WebResource javascript 方法 - WebForm_InitCallback()
- ES2015:从覆盖的类调用内部方法
- 是否可以检测父方法是否被覆盖
- 有没有任何方法可以覆盖浏览器渲染页面的方式
- 在IE8中恢复被覆盖的javascript方法
- javascript原生原型:扩展、添加和覆盖方法
- 覆盖原型方法
- Javascript 覆盖对象的方法
- XrayWrapper 错误(值是可调用的)在 Firefox 插件中覆盖原型方法时
- 是否可以覆盖本机 Es6 承诺解析方法
- 在 ES6 中调用覆盖方法库
- 保护公共方法,使其在 javascript 中被 chield 对象覆盖
- 找不到 Javascript 原型方法覆盖
- jquery widget 中的覆盖方法
- Javascript实现困境:寻找具有方法覆盖解决方案的类
- date.js解析方法覆盖Javascript解析方法