0

Func2 在我单击 button 时被调用。为什么我没有任何弹出窗口?我应该在第一个之后同时看到警报警报(“override1”)和警报(“override2”)吗?

// JavaScript Document
function person(name, surname) {
    this.name = "";
    this.surname = "";
    this.age = "11";
    this.setName(name);
    this.setSurname(surname);
    //alert('Person instantiated'); 
}
person.prototype.setName = function(name) {
    this.name = "Sir1" + name;
}
person.prototype.setSurname = function(surname) {
    this.surname = "-" + surname;
}
person.prototype.setAge = function(newAge) {
    this.age = newAge;
}
person.prototype.show = function() {
    alert("override1");
}
function employee(name, surname, company) {
    //if (arguments[0] === inheriting) return;
    person.call(this, name, surname); // -> override del costruttore
    //this.name = "Sir2"+name;
    this.company = company;
};
employee.prototype.show = function() {
    person.prototype.show;
    alert("override2");
}
function test2() {
    employee.prototype = new person();
    // correct the constructor pointer because it points to Person  
    employee.prototype.constructor = employee;
    // Crea un oggetto impiegato da persona
    impiegato = new employee("Antonio", "Di Maio", "Consuldimo");
    //impiegato.show();
    impiegato.show();
}​

谢谢

4

2 回答 2

1

test2()您将整个替换为employee.prototype的实例时person,从而用继承自的函数覆盖employee.prototype.show您之前定义的函数person。此外,正如代码框的答案所述,employee.prototype.show()您不是在调用person.prototype.show(),而只是在 void 上下文中对其进行评估,这根本没有任何效果。

在定义其原型上的任何其他方法之前,您必须设置employee's parent :

employee.prototype = new person();
employee.prototype.constructor = employee;
employee.prototype.show = function() { ... }

此外,当您调用父母的方法时,您需要自己提供正确的上下文:

person.prototype.show.call(this);
于 2012-07-30T15:06:55.963 回答
0

employee.prototype.show您没有调用该person.prototype.show方法时-将其更改为:

employee.prototype.show = function() {
     person.prototype.show();  
     alert ("override2");
 }
于 2012-07-30T15:04:32.763 回答