πŸ“– [JavaScript] μƒμ„±μž ν•¨μˆ˜

혱·2022λ…„ 9μ›” 5일

JavaScript_Intermediate

λͺ©λ‘ 보기
2/19

πŸ”Ž μƒμ„±μž ν•¨μˆ˜

첫 κΈ€μžλŠ” 보톡 λŒ€λ¬Έμžλ‘œ!
λΉ„μŠ·ν•œ 객체λ₯Ό μ—¬λŸ¬ 개 λ§Œλ“€ λ•Œ μ‚¬μš©
λΆ•μ–΄λΉ΅, μ™€ν”Œ 틀이라고 생각해보기~~

function User(name, age) {
	this.name = name;
	this.age = age;
}
let user1 = new User('Mike', 30);
let user2 = new User('Jane', 18); //new μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•΄μ„œ 호좜

βœ”οΈ λ™μž‘ 원리

function User(name, age) {
	//this = {} 
	this.name = name;
	this.age = age;
    //return this;
}
new ν•¨μˆ˜λͺ…();

βœ”οΈ μ–΄λ–€ ν•¨μˆ˜λΌλ„ newλ₯Ό λΆ™μ—¬μ„œ μ‹€ν–‰ν•˜λ©΄ λ™μž‘ 원리가 생성됨.

πŸ“Œ λ©”μ†Œλ“œ μΆ”κ°€

function User(name, age) {
	this.name = name;
	this.age = age;
    **this.sayName = function(){
    	console.log(this.name);
        } **
}
let user3= new User('Han', 65)
user3.sayName(); //'Han'

πŸ”— μ˜ˆμ‹œ

//μƒμ„±μž ν•¨μˆ˜: μƒν’ˆ 객체λ₯Ό μƒμ„±ν•΄λ³΄μž.

function Item(title, price){
  //this = {};
  
  this.title=title;
  this.price=price;
  this.showPrice = function(){
    console.log(`가격은 ${price}원 μž…λ‹ˆλ‹€.`);
  };
  
  //return this;
}

const item1 = new Item("μΈν˜•", 3000);
const item2 = new Item("κ°€λ°©", 40000);

console.log(item1) //Item {title:"μΈν˜•", price:3000, showPrice:f}

item2.showPrice(); //가격은 40000원 μž…λ‹ˆλ‹€.
profile
new blog: https://hae0-02ni.tistory.com/

0개의 λŒ“κΈ€