How to create Javascript Object using IIFE

2019-09-08 05:33发布

I have a Student object like the following,

function Student(){
      this.studentName = "";
}
Student.prototype.setStudentName=function(studentName){
      this.studentName = studentName;
}
Student.prototype.getStudentName=function(){
      return this.studentName;
}

It works when I do new Student();. But If I create the same Object like the following it gives an error,

(function(){

    function Student(){
          this.studentName = "";
    }
    Student.prototype.setStudentName=function(studentName){
          this.studentName = studentName;
    }
    Student.prototype.getStudentName=function(){
          return this.studentName;
    }
            })();

When I alert new Student(), I am getting an error Student is not defined. I tried writing return new Student() inside IIFE but didn't work for that also. How can I create Javascript objects using IIFE?

1条回答
萌系小妹纸
2楼-- · 2019-09-08 05:55

To make Student available outside the IIFE, return it and assign it to a global variable:

var Student = (function(){

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

    /* more code */

    return Student;
})();
查看更多
登录 后发表回答