How to create Javascript Object using IIFE

杀马特。学长 韩版系。学妹 提交于 2019-12-12 00:26:48

问题


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:


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


来源:https://stackoverflow.com/questions/32494821/how-to-create-javascript-object-using-iife

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!