如何使用IIFE创建Javascript对象 [英] How to create Javascript Object using IIFE
本文介绍了如何使用IIFE创建Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似于以下内容的Student对象,
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;
}
当我执行new Student();
时它可以工作.但是,如果我像下面那样创建相同的对象,则会出现错误,
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;
}
})();
当我向new Student()
发出警报时,出现错误Student is not defined
.
我尝试在IIFE中编写return new Student()
,但也没有用.如何使用IIFE创建Javascript对象?
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?
推荐答案
要使 Student 在IIFE之外可用,请将其返回并分配给全局变量:
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;
})();
这篇关于如何使用IIFE创建Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文