2012-07-30 98 views
0

当我点击按钮时调用Func2。为什么我没有弹出?我应该在第一次之后看到警报警报(“覆盖1”)和警报(“覆盖2”)吗?JavaScript中的替代

// 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(); 
}​ 

感谢

+0

我想你应该查看[markdown editing help](http://stackoverflow.com/editing-help/)页面。一个写得好的问题会给你写得很好的答案。 – zzzzBov 2012-07-30 15:03:06

+0

什么是'Func2'? – 2012-07-30 15:04:15

+0

什么按钮?您还没有张贴所谓的“测试2()” – Pointy 2012-07-30 15:04:22

回答

1

test2()你用person实例替换整个employee.prototype,从而使用从person继承的函数覆盖之前定义的employee.prototype.show函数。另外,正如编码框的回答中所述,在employee.prototype.show()中,您不是调用person.prototype.show(),而只是在无效的情况下对其进行评估,而这完全没有任何效果。

你必须设置employee的父定义其原型任何其他方法前:

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

此外,当你打电话给你父母的方法,你需要自己提供正确的上下文:

person.prototype.show.call(this); 
+0

你能帮我解决吗? – user1343454 2012-07-30 21:49:19

+0

@ user1343454:代码顺序很重要。你对'employee.prototype'所做的是:'array = [1];的Array.push(2);阵列= [];的Array.push(3);'。 – Jay 2012-07-31 01:54:03

+0

谢谢。 Lanzz的建议有所帮助。 – user1343454 2012-07-31 11:19:34

0

employee.prototype.show你是不是调用person.prototype.show方法 - 它改成这样:

employee.prototype.show = function() { 
    person.prototype.show(); 
    alert ("override2"); 
} 
+2

该方法将得到'person.prototype'为'this'这实在是意外的代码。 – Esailija 2012-07-30 15:06:03

+0

你funtion似乎我已经写在我的代码相同:( – user1343454 2012-07-30 21:23:04

+0

做,但我仍然只看到overide1警报消息:( – user1343454 2012-07-30 21:40:21