JavaScript ไม่มี class แบบดั้งเดิม (ก่อน ES6) ใช้ Module Pattern เพื่อห่อหุ้ม public/private methods และ variables ไว้ในออบเจกต์เดียว ใช้ IIFE (Immediately Invoked Function Expression) สร้าง scope แยก
ตัวอย่าง: ตรวจสอบผู้มีสิทธิเลือกตั้ง (อายุ 18 ปีขึ้นไป)
<!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>