gpt4 book ai didi

javascript - 使用iffe vs构造函数在js中创建对象

转载 作者:行者123 更新时间:2023-11-29 19:23:29 25 4
gpt4 key购买 nike

有什么区别

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

对比

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");

最佳答案

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

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

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

所以使用第二个代码段,它更短两行,也更清晰。

关于javascript - 使用iffe vs构造函数在js中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com