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

Thêm method vào object constructor trong JavaScript

Thêm method vào object constructor khác với object thường. Không thể thêm method bên ngoài như object thường. Phải thêm bên trong constructor.

Ví dụ

Method được thêm trong constructor, nên lấy được giá trị hợp lệ.

<html> <body> <script>    function Business(name, property, age, designation) {       this.Name = name;       this.prop = property;       this.age = age;       this.designation = designation;       this.name = function() {          return this.Name       };    }    var person1 = new Business("Trump", "$28.05billion", "73", "President");    document.write(person1.name()); </script> </body> </html>

Kết quả

Trump

Lưu ý: Cách này tạo method mới cho mỗi instance (tốn bộ nhớ). Hiện đại hơn: dùng class với method trong prototype, hoặc prototype.method = ... sau constructor.