2017-09-25 38 views
-1

在JavaScript OOPS中繼承時獲取未定義的值。學生對象不繼承Person對象在JavaScript中繼承時獲取未定義的值OOPS

function person(name, age) { 
 
    this.name = name; 
 
    this.age = age; 
 
    this.say = function() { 
 
     return this.name + " says Hi.."; 
 
    } 
 
} 
 

 
var p1 = new person("Mahesh", "33"); 
 
var p2 = new person("Girish", "30"); 
 

 
console.log(p1.say()); 
 
console.log(p2.say()); 
 

 
// Inheritance 
 
function student() {}; 
 
student.prototype = new person(); 
 
var stud1 = new student("Nakktu", "32"); 
 

 
console.log(stud1.say());

回答

1

您還必須從子類的構造函數中調用你的超類。有關更多信息,請參閱this MDN鏈接。

function person(name, age) { 
 
    // When no name is provided, throw an error. 
 
    if (name === undefined) { 
 
     throw 'Unable to create instance of person. Name is required.'; 
 
    } 
 
    
 
    this.name = name; 
 
    this.age = age; 
 
    this.say = function() { 
 
     return this.name + " says Hi.."; 
 
    } 
 
} 
 

 
var p1 = new person("Mahesh", "33"); 
 
var p2 = new person("Girish", "30"); 
 

 
console.log(p1.say()); 
 
console.log(p2.say()); 
 

 
// Inheritance 
 
function student(name, age) { 
 
    // You need to call your super class. 
 
    person.call(this, name, age); 
 
}; 
 
// Don't use "new person()", your code will stop working when person() throws 
 
// an error when the 'name' param is required and missing. 
 
student.prototype = Object.create(person.prototype); 
 

 
var stud1 = new student("Nakktu", "32"); 
 
console.log(stud1.say());

+0

謝謝@Thijs。這將有助於我更好地理解「繼承」。 :-) – maheshv13

+0

我已經更新了答案,在未提供名稱時拋出一個錯誤。當您將'student.prototype ='賦值更改回'new person();'時,您將看到代碼失敗,而當前實現仍然按預期工作。 – Thijs