繁体   English   中英

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

您仍然必须从子类的构造函数中调用您的超类。 有关更多信息,请参阅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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM