我有一个如下的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对象?

最佳答案

要使学生可以在IIFE之外使用,请将其返回并分配给全局变量:

var Student = (function(){

    function Student(){
      this.studentName = "";
    }

    /* more code */

    return Student;
})();

10-07 21:49