๐ŸŒฑ → ๐ŸŒณ

[JavaScript] JS ๊ธฐ์ดˆ ๋งˆ๋ฌด๋ฆฌ ๋ณธ๋ฌธ

Client/Javascript

[JavaScript] JS ๊ธฐ์ดˆ ๋งˆ๋ฌด๋ฆฌ

BAY 2022. 7. 15. 16:13
728x90

๐Ÿ“Œ Object

์ ‘๊ทผ

์ถ”๊ฐ€

์‚ญ์ œ

ํ”„๋กœํผํ‹ฐ ์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ

 

Object method

method: ๊ฐ์ฒด property๋กœ ํ• ๋‹น ๋œ ํ•จ์ˆ˜

 

๐Ÿ“Œ this

function sayHello() {
  console.log(`Hello, I'm ${this.name}`);
  console.log(this);
}
let boy = {
  name: "Justin",
  sayHello,
};
let girl = {
  name: "Anna",
  sayHello,
};
boy.sayHello(); //Hello, I'm Justin
girl.sayHello(); //Hello, I'm Anna

console ํ™•์ธ

โœ…  ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์™€ this

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ์ผ๋ฐ˜ ํ•จ์ˆ˜์™€๋Š” ๋‹ฌ๋ฆฌ ์ž์‹ ๋งŒ์˜ this๋ฅผ ๊ฐ€์ง€์ง€ ์•Š์Œ 

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ this๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ๊ทธ this๋Š” ์™ธ๋ถ€์—์„œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ด

let showHeight = () => {
  console.log(this.height);
  console.log(this);
};

const showName = () => {
  console.log(this.name);
  console.log(this);
};

const pororo = {
  name: "๋ฝ€๋กœ๋กœ",
  height: 70,
  weight: 50,
  gender: "None",
  showName,
  showHeight,
};
const rupy = {
  name: "๋ฃจํ”ผ",
  height: 50,
  showName,
  showHeight,
};
pororo.showName();
pororo.showHeight();
rupy.showName();
rupy.showHeight();

ํ™”์‚ดํ‘œํ•จ์ˆ˜์˜ ์ƒ์œ„์ธ ๋ธŒ๋ผ์šฐ์ € ํ™˜๊ฒฝ window๊ฐ€ ๋ฐ˜ํ™˜๋จ

 

๐Ÿ“Œ ์ƒ์„ฑ์ž ํ•จ์ˆ˜

์ค‘๋ณต๊ฐ’์„ ๊ฐ€์ง€๋Š” ๋ณ€์ˆ˜๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ํŽธ๋ฆฌ

function Fruits(name, price) {
  this.name = name;
  this.price = price;
  this.showPrice = function () {
    console.log(`${this.name}์˜ ๊ฐ€๊ฒฉ์€ ${this.price}์ž…๋‹ˆ๋‹ค.`);
  };
}
let orange = new Fruits("์˜ค๋ Œ์ง€", 3000);
let dragonFruit = new Fruits("์šฉ๊ณผ", 2500);
let banana = new Fruits("๋ฐ”๋‚˜๋‚˜", 2000);
let pineApple = new Fruits("ํŒŒ์ธ์• ํ”Œ", 5000);

orange.showPrice();
dragonFruit.showPrice();
banana.showPrice();
pineApple.showPrice();

์ฃผ์˜,

  • ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ช… ์ฒซ๊ธ€์ž ๋Œ€๋ฌธ์ž ์‚ฌ์šฉ 
  • function์•ˆ์— , ๊ฐ€ ์•„๋‹Œ ; ์‚ฌ์šฉ 
  • new ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ˜ธ์ถœ
728x90