繁体   English   中英

如何使用 javascript 构造函数,它显示未定义错误

[英]How do I use javascript constructor, its showing undefine error

function student() {
  name = "abhi";
  branch = "iiot";
  intro = function () {
    return "student name is" + this.name + "of" + this.branch;
  };
}

function student1() {
  yr_of_stud = "first";
}
student1.prototype.getDetl = function () {
  return this.intro() + "studying in " + this.yr_of_stud + `in ${this.clg}`;
};
student1.prototype.clg = "usar";

student1.prototype = new student();
var obj = new student1();
console.log(obj.name);
console.log(obj.branch);
console.log(obj.clg);
console.log(obj.yr_of_stud);
console.log(obj.intro());
console.log(obj.getdetl());

它显示未定义,对于最后两个,它显示 function 错误。 第一个 function 存储名称和分支,在第二个 function 采用第一个 function 并更新。

构造函数是一种特殊方法,只能与从 class 创建的 object 一起使用。 因此,您必须创建一个Student class 才能使用它。

如果您想了解有关课程的更多信息,我建议您查看MDN Web 文档

您可以通过多种方式定义类,但对于本示例,我将使用 class 声明。

 class Student { constructor(name, branch, year, college) { this.name = name; this.branch = branch; this.year = year; this.college = college; } intro() { return `The student's name is ${this.name} of the branch ${this.branch}`; } detl() { return this.intro() + ` and is studying in their ${this.year} year in the college ${this.college}`; } } let student1 = new Student("abhi", "iiot", "first", "usar"); console.log(student1.name); console.log(student1.branch); console.log(student1.college); console.log(student1.year); console.log(student1.intro()); console.log(student1.detl());

暂无
暂无

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

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