下面是我的JS代码:
var Person=function(name,age)
{
this.name=name;
this.age=age;
}
Person.prototype.calculateAge=function()
{
console.log(2016-this.age);
}
var Teacher=function(salary)
{
this.salary=salary;
}
Teacher.prototype.calculateAge=function() // Ovverriding the fucntion calculateAge
{
console.log("welcome to my world");
}
var pp=new Person('john',31); // creating object pp, pp.name // john
Teacher.prototype=pp;
var t= new Teacher(20); // inherit name and age , t.name // john
// now here am confused
t.calculateAge() // 1990 but am ovverride it will print my console right
//
谁能解释一下我该如何覆盖?在这里,当我重写计算年龄函数时,通过调用 t.calculateAge() 其打印继承了一个
最佳答案
这段代码可能有效:
function Person(name,age)
{
this.name=name;
this.age=age;
}
Person.prototype.calculateAge=function()
{
console.log(2016-this.age);
}
function Teacher(salary)
{
this.salary=salary;
}
Teacher.prototype = new Person();
Teacher.prototype.calculateAge=function() // Ovverriding the fucntion calculateAge
{
console.log("welcome to my world");
}
var t= new Teacher(20); // inherit name and age , t.name // john
// now here am confused
t.calculateAge() // 1990 but am ovverride it will print my console right
//
关于javascript - javascript中的继承和覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670841/