Thêm property vào object constructor khác với object thường. Phải thêm trong constructor, không phải bên ngoài.
Ví dụ 1: Sai - Thêm bên ngoài
Thêm property như object thường. Vì dùng constructor, property ngoài constructor trả về undefined.
<html> <body> <p id = "prop"></p> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; } Business.language = "chinese"; var person1 = new Business("Trump", "$28.05billion", "73", "President"); var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur"); document.write(person2.language); </script> </body> </html>
Kết quả
undefined
Ví dụ 2: Đúng - Thêm trong constructor
<html> <body> <p id = "prop"></p> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; this.language = "chinese"; } var person1 = new Business("Trump", "$28.05billion", "73", "President"); var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur"); document.write(person2.language); </script> </body> </html>
Kết quả
chinese
Giải thích: Business.language = ... gán property cho function Business (là object), không phải instance. Instance chỉ có property gán qua this trong constructor.