๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“’ JavaScript

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ๊ฐ์ฒด

by Tamii 2021. 2. 22.
๋ฐ˜์‘ํ˜•

prototype ์€ ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋“ค์ด ์—ฌ๋Ÿฌ๊ฐœ ์ž‡์–ด๋„ ๋™์ผํ•œ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์—์„œ ํšจ์œจ์ ์œผ๋กœ ์žฌ์‚ฌ์šฉ๋จ 

 

๊ฐ์ฒด๋“ค์ด ๊ฐ™์€ ๊ณต๊ฐ„์„ shareํ•˜๋Š” ๊ฒƒ prototype

 

โ– this ๋กœ function ์ •์˜ ํ–ˆ์„ ๊ฒฝ์šฐ

const Health = function(name, healthTime) {
  this.name = name;
  this.healthTime = healthTime;
  this.showHealth = function() {
  	return this.name  + this.lastTime + "์šด๋™์™„๋ฃŒ";
	}
}

const h1 = new Health("tami", "12:12");
const h2 = new Health("recoder", "02:12");

h1.showHealth === h2.showHealth // false

โ– Prototype์œผ๋กœ ์ •์˜ํ•œ ๊ฒฝ์šฐ

const Health = function(name, healthTime) {
  this.name = name;
  this.healthTime = healthTime;
}

Health.prototype.showHealth = function() {
  console.log(this.name + this.healthTime + "์šด๋™์™„๋ฃŒ";
}


const h1 = new Health("tami", "12:12");
const h2 = new Health("recoder", "02:12");

h1.showHealth === h2.showHealth // true

h1 ๊ณผ h2 ๋Š” ๊ฐ™์€ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์— ๋“œ๋Ÿฌ์ž‡๋Š” showHealth ๋ฅผ ๊ณต์œ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ ์ƒ์Šน

 

๋ฉ”์„œ๋“œ == prototype์— ๋งŽ์ด ๋ณด๊ด€ํ•˜๋Š” ํŽธ 

๋Œ“๊ธ€