2017-08-14 92 views
0

下面是我的JS代码:继承和压倒一切的JavaScript

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()其打印继承一个

+0

看到这个:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance – ZAhmed

+0

我检查了这么多的博客和视频也困惑,我重写calculateAge功能的权利,但是我打电话t.calculateAge(),它将打印latestone,但在这里印刷的父母,我们在这种情况下如何ovverride,如何其workes –

+0

改进的语言和做出格式更改 –

回答

0

此代码的工作可能:

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 
    // 
+0

是,工作,但在这里我有小疑问, Teacher.prototype =新的Person(“约翰福音”,20); 变种T =新教师(20)//t.name=john,t.age = 20 K精, 但“我重写在教师目标calculatingAge()温控功能,你正在创建的对象采取Teacher.prototype,我想人calculateAge()函数,然后我们如何实现, 非常感谢回复,我很困惑了很多我有这么多的疑惑#ZAhmed –

+0

我不明白,你的意思是什么 – ZAhmed

+0

这里如何调用calculateAge()// Function for Person,t.calculateAge()它将通过以下方式为Teacher对象 –

0

Teacher.prototype.calculateAge = function() ...应行Teacher.prototype = pp后。

否则,Teacher.prototype = pp会将Teacher.prototype重置为pp

而且,t.calculateAge()输出1985对于2016 - 31 = 1985

+0

Thanq @leaf,我想打印超驰功能()的结果,即执行console.log()O/p, –