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

Getting undefined value while inheritance in JavaScript OOPS

在 JavaScript OOPS 中继承时获取未定义的值。 Student 对象不继承 Person 对象

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());

您仍然需要从子 class 的构造函数中调用您的超级 class。有关详细信息,请参阅 this MDN link。

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());