JavaScript本机不支持类,因此使用Module模式。这是为了将公共,私有方法和变量存储在单个对象中。为了使用和理解它,我们将解决匿名关闭问题,以显示由于未达到18岁年龄标准而导致的选民资格丧失。
您可以尝试运行以下代码来了解JavaScript模块模式
<!DOCTYPE html>
<html>
<body>
<script>
(function () {
var votersAge = [15, 50, 27, 17, 22, 87, 65, 45];
var average = function() {
var total = votersAge.reduce(function(accumulator, age) {
return accumulator + age}, 0);
return total / votersAge.length + '.';
}
var notQualified = function(){
var notAdult = votersAge.filter(function(age) {
return age < 18;});
return 'Voters not qualified to vote (age less than 18) = ' + notAdult.length;
}
document.write(notQualified());
}());
</script>
</body>
</html>