JavaScript Introduction | Objects
What Is an Object?
An object can be understood as a thing that we can recognize in real life.
Example of an Object
Object
- cat kitty
Property
- cat.name = “Nabi”
- cat.family = “Korean Shorthair”
- cat.age = 0.1
- cat.weight = 300
Method
- cat.mew()
- cat.eat()
- cat.sleep()
- cat.play()
All cat objects have properties like the above, but the value of each property will differ for each instance.
JavaScript Objects
The basic data type in JavaScript is the object.
An object is an unordered set of properties made up of names and values. A function can also be used as the value of a property, and such a property is called a method.
var cat = "Nabi"; // Declaration of a normal variable
// An object is also a kind of variable that holds many values.
var kitty = { name: "Nabi", family: "Korean Shorthair", age: 1, weight: 1.1 };
cat // Nabi
kitty.name // Nabi
In JavaScript, everything except numbers, strings, booleans, and the undefined type is an object.
However, primitive types such as numbers, strings, and booleans are treated as objects with fixed values, so they also have object-like characteristics.
Referring to Object Properties
In JavaScript, object properties can be referenced as follows.
Syntax
objectName.propertyName
or
objectName["propertyName"]
var person = {
name: "Hong Gil-dong", // Define the name property.
birthday: "030219", // Define the birthday property.
pId: "1234567", // Define the personal ID property.
fullId: function() { // Return a resident registration number by combining birthday and personal ID.
return this.birthday + this.pId;
}
};
person.name // Hong Gil-dong
person["name"] // Hong Gil-dong
Referring to Object Methods
In JavaScript, object methods can be referenced as follows.
Syntax
objectName.methodName()
var person = {
name: "Hong Gil-dong",
birthday: "030219",
pId: "1234567",
fullId: function() {
return this.birthday + this.pId;
}
};
person.fullId() // 0302191234567
person.fullId; // function () { return this.birthday + this.pId; }
If parentheses (()) are not added after the method name when referencing a method, the property itself is referenced instead of calling the method.
Therefore, when the property itself is referenced without using parentheses, the definition of that method itself is returned.