Factpry function는 (새로운)객체를 리턴하는 함수
function makeColor(r, g, b) {
const color = {};
color.r = r;
color.g = g;
color.b = b;
color.rgb = function () {
const { r, g, b } = this;
return `rgb(${r},${g},${b})`;
};
color.hex = function () {
const { r, g, b } = this;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
return color;
}
makeCOlor()
함수를 사용해서 color
라는 새로운 객체를 만들고
r
, g
, b
parameter를 객체 안에 저장
color
객체의 rgb()
메소드는 rgb 색상을 출력하는 메소드
color
객체의 hex()
메소드는 hex 색상을 출력하는 메소드
const color = makeColor(255, 255, 255);
- 변수
color
에 makeColor()
함수를 사용해 3개의 parameter를 넣어주면
console.log(color.rgb());
console.log(color.hex());
Constructor function은 new 키워드를 사용하여 객체를 생성하는 함수
생성자 함수는 유사한 객체를 여러 개 생성해야 할 때 활용, 함수명은 대문자로 시작
function Color(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
Color.prototype.rgb = function () {
const { r, g, b } = this;
return `rgb(${r},${g},${b})`;
};
Color.prototype.rgba = function (a = 1.0) {
const { r, g, b } = this;
return `rgb(${r},${g},${b},${a})`;
};
Color.prototype.hex = function () {
const { r, g, b } = this;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
const color1 = new Color(12, 12, 12);
const color2 = new Color(21, 21, 21);
color1.rgba(0.3);
Class
class Color {
constructor(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
this.name = name;
}
innerRgb() {
const { r, g, b } = this;
return `${r},${g},${b}`;
}
rgb() {
return `rgb(${this.innerRgb()})`;
}
rgba(a = 1.0) {
return `rgb(${this.innerRgb()},${a})`;
}
hex() {
const { r, g, b } = this;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
}
const color3 = new Color(255, 99, 71);
class extends & super
class Pet {
constructor(name, age) {
console.log("Pet constructor");
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating!!!`;
}
}
class Cat extends Pet {
constructor(name, age, life = 9) {
console.log("Cat constructor");
super(name, age);
this.life = life;
}
mew() {
return "MEOWWWWWW";
}
}
class Dog extends Pet {
bark() {
return "WOOOOOOOF";
}
}