โœ’๏ธ JavaScript Object (Basic)

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

  1. By object literal
  2. By creating instance of Object directly
  3. 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);
ยฉ 2021 blog