【发布时间】: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