Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách định nghĩa hàm trong JavaScript

1. Function Declaration (Khai báo hàm)

function functionName(parameters) {
  // body
  return value;
}

// Hoisting: có thể gọi trước khi khai báo
sayHello("An");

function sayHello(name) {
  console.log("Hello " + name);
}

2. Function Expression (Biểu thức hàm)

// Anonymous
var greet = function(name) {
  return "Hello " + name;
};

// Named (debug tốt hơn)
var factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);
};

// Arrow function (ES6) – ngắn gọn, lexical this
const add = (a, b) => a + b;
const greet = name => `Hello ${name}`;

3. Function Constructor (hiếm dùng)

var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2,3)); // 5
// Không khuyến khích: eval-like, bảo mật, hiệu năng

4. Method trong Object/Class

// Object literal
const obj = {
  sayHi() { console.log("Hi"); }
};

// Class (ES6)
class Person {
  constructor(name) { this.name = name; }
  greet() { console.log("Hi " + this.name); }
}

So sánh nhanh

LoạiHoistingthisDùng khi
DeclarationCóDynamicHàm tiện ích toàn cục
Expression (var)KhôngDynamicCallback, conditional define
Arrow functionKhôngLexical (bảo toàn this)Callback, method ngắn, functional
Method/ClassKhôngDynamic (instance)OOP, object behavior

Best practice

  • Mặc định dùng arrow function cho callback, function expression.
  • Dùng function declaration cho hàm top-level cần hoisting.
  • Dùng method shorthand trong object/class.
  • Tránh new Function().