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

Cách in tất cả phương thức (methods) của một đối tượng trong JavaScript

Để lấy tất cả phương thức, dùng Object.getOwnPropertyNames() kết hợp lọc kiểu function.

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write("<br>" + Object.getOwnPropertyNames(Math).filter(function(p) {
        return typeof Math[p] === 'function';
      }));
    </script>
  </body>
</html>

Giải thích: Object.getOwnPropertyNames(obj) trả về mảng tên thuộc tính riêng (own properties) của object (kể cả non-enumerable). Lọc typeof === 'function' để lấy method.

Lưu ý: Không lấy được method kế thừa từ prototype. Dùng for...in hoặc lặp qua prototype chain nếu cần.