【问题标题】:How to create Javascript Object using IIFE如何使用 IIFE 创建 Javascript 对象
【发布时间】:2015-12-06 07:46:35
【问题描述】:

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

【问题讨论】:

  • 尝试将function Student(){this.studentName = "";}放在IIFE之外。
  • Student 的函数声明在 IIFE 内部,但您的调用在外部。顺便说一句,在这里使用 IIFE 有点毫无意义。唯一的结果是隐藏Student,显然你不想隐藏它。 ;-)

标签: javascript javascript-objects iife


【解决方案1】:

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

var Student = (function(){

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

    /* more code */

    return Student;
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多