2017-08-14 84 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, –