const key = "name";
const obj = {
[key]: "철수"
}
console.log(obj.name)
함수 선언과 동시에 실행 → 전역 범위를 오염시키지 않고 싶을 때 사용
{function greet(){
console.log('Hello')
})()
(function(){
console.log('Hello2')
})()
{()=>{
console.log('Hello3')
})()
// 매개변수 추가
{function greet(name){
console.log('Hello, ' + name)
})("철수")
함수로 객체를 정의
function sUer(){
this.name = '철수',
this.age = 30
}
const u = new User();
console.log(n)
function Car(name, color) {
this.name = name;
this.color = color;
}
const car = new Car("benz", "white");
console.log(car.name);
console.log(car.color);
const car2 = new Car("bmw", "black");
console.log(car2.name);
console.log(car2.color);
인스턴스
function Car(name, color) {
this.name = name;
this.color = color;
this.getIngo = function (){
return `${this.name} ${this.color}`
}
}
const car = new Car("benz", "white");
프로토타입 체인 또는 프로토타입 체이닝
고급 패턴 중
프라이빗
프로토타입에 함수를 뺄수 없다는 것 빼고 고유성 좋음
function Counter() {
let count = 0;
this.increment = function () {
count++;
};
this.decrement = function () {
count--;
};
this.getCount = function () {
return count;
};
}
const counter = new Counter();
counter.increment();
counter.increment();
counter.increment();
console.log(counter.getCount());
function BankAccount(init) {
let balance = init;
this.deposit = function (amount) {
balance += amount;
};
this.withdraw = function (amount) {
balance -= amount;
};
this.getBalance = function () {
return balance;
};
}
const woori = new BankAccount(1000);
woori.deposit(2000);
woori.balance = 10000000;
console.log(woori.balance);
console.log(woori.getBalance());
// function BankAccount(init) {
// this.balance = init;
// }
// BankAccount.prototype.deposit = function (amount) {
// this.balance += amount;
// };
// BankAccount.prototype.withdraw = function (amount) {
// this.balance -= amount;
// };
// const woori = new BankAccount(1000);
// woori.deposit(2000);
// woori.balance = 10000000;
// console.log(woori.balance);
생성자 함수 팩토리 패턴
function createPerson(type, name) {
function Employee(name) {
this.name = name;
this.type = "employee";
}
function Manager(name) {
this.name = name;
this.type = "maanger";
}
switch (type) {
case "employee":
return new Employee(name);
case "maanger":
return new Manager(name);
}
}
상속
function Person(name) {
this.name = name;
}
Person.prototype.introduce = function () {
return `I am ${this.name}`;
};
function Developer(name, position) {
this.name = name;
this.position = position;
}
// 프로토타입
Developer.prototype = Object.create(Person.prototype);
Developer.prototype.constructor = Developer;
Developer.prototype.skill = function () {
return this.position;
};
const dev = new Developer("철수", "프론트개발자");
console.dir(dev).introduce();
console.dir(dev).skill();