JavaScript allows developers to define custom objects beyond built - in methods and classes. There are three primary syntaxes for creating custom objects:
1. Using the Built - in Object Constructor
To create an object with the system - provided Object constructor, you can do the following:
// Instantiate an object
let user = new Object();
// Add properties to the object
user.username = "Li Si";
user.age = 28;
user.gender = "Female";
// Add a method to the object
user.play = function (game) {
console.log(this.username + " is playing " + game);
};
// Access object properties
console.log(user.username);
console.log(user.age);
console.log(user.gender);
// Call the object's method
user.play("Chess");
2. Using a Custom Cnostructor Function
You can also create a custom cosntructor function to generate objects:
// Define a constructor function
function Student(sName, sGrade) {
this.studentName = sName;
this.grade = sGrade;
this.study = function (subject) {
console.log(this.grade + " - grade student " + this.studentName + " is studying " + subject);
};
}
let s1 = new Student("Wang Wu", 5);
// Access object properties
console.log(s1.studentName);
console.log(s1.grade);
// Call the object's method
s1.study("Math");
3. Using Object Literal (JSON - like) Syntax
The object literal syntax (similar to JSON format) is a concise way to create objects:
/*
Object literal format:
let objectName = {
propertyName: propertyValue,
methodName: function() { ... }
};
*/
let profile = {
fullName: "Xiao Hong",
gender: "Female",
age: 12,
read: function (book) {
console.log(this.age + " - year - old " + this.gender + " " + this.fullName + " is reading " + book);
}
};
// Access object properties
console.log(profile.fullName);
console.log(profile.gender);
console.log(profile.age);
// Call the object's method
profile.read("Fairy Tales");