如何使用 IIFE 创建 Javascript 对象
How to create Javascript Object using IIFE
我有一个如下所示的 Student 对象,
function Student(){
this.studentName = "";
}
Student.prototype.setStudentName=function(studentName){
this.studentName = studentName;
}
Student.prototype.getStudentName=function(){
return this.studentName;
}
当我new Student();
时它起作用了。但是如果我像下面这样创建相同的对象,它会出错,
(function(){
function Student(){
this.studentName = "";
}
Student.prototype.setStudentName=function(studentName){
this.studentName = studentName;
}
Student.prototype.getStudentName=function(){
return this.studentName;
}
})();
当我提醒 new Student()
时,我收到一个错误 Student is not defined
。
我尝试在 IIFE 中编写 return new Student()
但也没有用。如何使用 IIFE 创建 Javascript 对象?
要使 Student 在 IIFE 之外可用,return 并将其分配给全局变量:
var Student = (function(){
function Student(){
this.studentName = "";
}
/* more code */
return Student;
})();
我有一个如下所示的 Student 对象,
function Student(){
this.studentName = "";
}
Student.prototype.setStudentName=function(studentName){
this.studentName = studentName;
}
Student.prototype.getStudentName=function(){
return this.studentName;
}
当我new Student();
时它起作用了。但是如果我像下面这样创建相同的对象,它会出错,
(function(){
function Student(){
this.studentName = "";
}
Student.prototype.setStudentName=function(studentName){
this.studentName = studentName;
}
Student.prototype.getStudentName=function(){
return this.studentName;
}
})();
当我提醒 new Student()
时,我收到一个错误 Student is not defined
。
我尝试在 IIFE 中编写 return new Student()
但也没有用。如何使用 IIFE 创建 Javascript 对象?
要使 Student 在 IIFE 之外可用,return 并将其分配给全局变量:
var Student = (function(){
function Student(){
this.studentName = "";
}
/* more code */
return Student;
})();