javascript - javascript中的继承和覆盖

标签 javascript jquery

下面是我的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/

相关文章:

javascript - Jquery 不会替换文本区域中的文本

javascript - Blur() 与 onblur()

jQuery - 根据父元素类向子元素添加 CSS

javascript - localStorage + jQuery 自动保存和加载 p

javascript - 有没有更好的方法来对对象数组进行排序以动态生成按值分隔的 HTML 元素?

javascript - 如何计算div中许多图像的总宽度?

javascript - 动态加载的项目不会在模式中转向 Owl Carousel

javascript - 在测试 Web 应用程序时,我是否应该担心使用 selenium 发送纯文本密码

JavaScript 单例模式和 'this'

javascript - 奇怪的重定向错误