使用iffe vs constructor在js中创建对象

时间:2015-08-17 16:11:21

标签: javascript iife

之间有什么区别
var Student = (function () {
function Student(firstname, middleinitial, lastname) {
    this.firstname = firstname;
    this.middleinitial = middleinitial;
    this.lastname = lastname;
    this.fullname = firstname + " " + middleinitial + " " + lastname;
}
return Student;})();

VS

function Student(firstname, middleinitial, lastname) {
    this.firstname = firstname;
    this.middleinitial = middleinitial;
    this.lastname = lastname;
    this.fullname = firstname + " " + middleinitial + " " + lastname;
}

在创建新对象时使用哪一个?

var temp=new Student("john","R","wayne");

1 个答案:

答案 0 :(得分:3)

由于你的IIFE除了创建Student函数之外什么都不做,它完全等同于

var Student = function Student(firstname, middleinitial, lastname) {
    this.firstname = firstname;
    this.middleinitial = middleinitial;
    this.lastname = lastname;
    this.fullname = firstname + " " + middleinitial + " " + lastname;
}

由于您没有在模块范围内引入任何局部变量,因此没有理由将其包装在IIFE中。

所以使用第二个片段,它的两条线更短更清晰。