Objects in JavaScript
JavaScript object is an entity having state and behavior
(properties and method).
JavaScript is an object-based language.
Everything is an object in JavaScript
This is in the form of "key : value" pair
var coffee = {
name: "mocha",
size: "Tall",
hotcold: "cold"
}
console.log(`${coffee.name}`);
Objects can be created in 3 different ways
- By object literal
- By creating instance of Object directly
- By using an object constructor
[1] Javascript Object by object literal
๋ฆฌํฐ๋ด ๋ฐฐ์ด์ ์ด์ฉํ ์ค๋ธ์ ํธ ์์ฑ
coffee = {
id: 1,
name: "mocha",
price: 6000
}
console.log(coffee.id + " " + coffee.name + " " coffee.price);
[2] By creating instance of Object
The syntax of creating object directly is
new ์์ฑ์๋ฅผ ์ด์ฉํ ์ค๋ธ์ ํธ ์์ฑ
var coffee = new Object();
coffee.id = 1;
coffee.name = "mocha";
coffee.price = 6000;
console.log(coffee.id + " " + coffee.name + " " coffee.price);
[3] Using constructor
In this you need to create function with arguments.
Each argument value can be assigned in the current object by using this keyword.
ํจ์๋ฅผ ์ ์ธํ์ฌ new์์ฑ์๋ก ์์ฑํ ์ค๋ธ์ ํธ์ ์ธ์๋ฅผ ์ ๋ฌ
function coffee(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
c = new coffee(1, "mocha", 6000);
console.log(c.id + " " + c.name + " " + c.price);