在JavaScript OOPS中继承时获取未定义的值

时间:2017-09-25 09:38:41

标签: javascript javascript-objects prototypal-inheritance

在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 个答案:

答案 0 :(得分: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());