TIL025_210419
🍊 감상
📙 열품타 코딩 시간 5hour
👍🏼 -
👎🏼 -
🚀 목표
- Udemy에서 Javascript 강좌 수강하기 (365/682)
- 개인 프로젝트 진행
📣 The Web Developer Bootcamp 2021
29. Prototypes, classes & OOP
295. Factory function
function rgb(r, g, b) {
return `rgb(${r},${g},${b})`;
}
function makeColor(r, g, b) {
//building an object
const color = {}; //make empty object
color.r = r; //property
color.g = g;
color.b = b;
color.rgb = function () {
//method
//console.log(this); //{r:35, g:355, b:150, rgb:f}
const { r, g, b } = this; //refer to color object
return `rgb(${r},${g},${b})`;
};
color.hex = function () {
const { r, g, b } = this; //refer to color object
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
return color;
}
const firstColor = makeColor(35, 355, 150);
firstColor.rgb();
firstColor.hex();
// in this method, the value of this will refer to the object to the left of the dot
296. Constructor functions
29. Prototypes, classes & OOP
295. Factory function
function rgb(r, g, b) {
return `rgb(${r},${g},${b})`;
}
function makeColor(r, g, b) {
//building an object
const color = {}; //make empty object
color.r = r; //property
color.g = g;
color.b = b;
color.rgb = function () {
//method
//console.log(this); //{r:35, g:355, b:150, rgb:f}
const { r, g, b } = this; //refer to color object
return `rgb(${r},${g},${b})`;
};
color.hex = function () {
const { r, g, b } = this; //refer to color object
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
return color;
}
const firstColor = makeColor(35, 355, 150);
firstColor.rgb();
firstColor.hex();
// in this method, the value of this will refer to the object to the left of the dot
296. Constructor functions
why the factory function is not commonly used, instead why we commonly use constructor pattern or constructor function
new is an operator
new XMLHttpRequest();
//this makes us a new object following a pattern
const firstColor = makeColor(35, 355, 150);
firstColor.rgb();
firstColor.hex();
const black = makeColor(0, 0, 0);
firstColor.rgb();
firstColor.hex();
console.log(black.hex === firstColor.hex) //false
console.log("hi".slice === "bye".slice) //true
What's happening here?
slice method is not defined on every single string -> they are defined on the prototype
instead of having their own method copy, they are referencing one function and it's located on the prototype
function Color(r,g,b) {
this.r = r;
this.g = g;
console.log(this); //window -> global scope
}
하지만 new 사용하면 new object를 만들어줌 based off of this pattern
- links (sets the constructor of) this object to another object
(now we can add the method not to the individual objects, not to the instances, to the prototype)
new keyword -> makes new object, returns the object`
function Color(r,g,b) {
this.r = r;
this.g = g;
console.log(this); //window -> global scope
}
Color(255,0,0) //window {...}
new Color(255,0,0) //Color{r:255,g:0,b:0}
코드 new Foo(...)가 실행될 때 다음과 같은 일이 발생한다:
- Foo.prototype을 상속하는 새로운 객체가 하나 생성된다.
Creates a blank, plain JavaScript object. - 명시된 인자 그리고 새롭게 생성된 객체에 바인드된 this와 함께 생성자 함수 Foo가 호출된다.new Foo는 new Foo()와 동일하다. 즉 인자가 명시되지 않은 경우, 인자 없이 Foo가 호출된다.
Adds a property to the new object (__proto__)
that links to the constructor function's prototype object
Properties/objects added to the construction function prototype are therefore accessible to all instances created from the constructor function (using new).
3. 생성자 함수에 의해 리턴된 객체는 전체 new 호출 결과가 된다. 만약 생성자 함수가 명시적으로 객체를 리턴하지 않는 경우, 첫 번째 단계에서 생성된 객체가 대신 사용된다.(일반적으로 생성자는 값을 리턴하지 않는다. 그러나 일반적인 객체 생성을 재정의(override)하기 원한다면 그렇게 하도록 선택할 수 있다.)
Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
Returns this if the function doesn't return an object.
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.hex = function () {
const { r, g, b } = this;
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
Color.prototype.rgba = function (a = 1.0) {
const { r, g, b } = this;
return `rgba(${r},${g},${b},${a})`;
};
const color1 = new Color(40, 50, 60);
const color2 = new Color(0, 0, 0);
color1.hex(); //color1 will be the value of 'this'
console.log(color1.hex === color2.hex); //they are pointing to the same thing
//they are on the shared proototype of object rather than uniquely defined on each instance
document.body.style.backgroundColor = color1.rgba();
Javascript Classes
syntactic sugar
class Color {
constructor(r, g, b) {
//constructor is a function that will execute immediately
//whenever a new color is created
//whenever we instantiate a new instance of Color
console.log(r, g, b, name);
this.r = r;
this.g = g;
this.b = b;
this.name = name;
}
greet() {
return `hello ${this.name}`;
}
innerRGB() {
const { r, g, b } = this;
return `${r},${g},${b}`; //'255,255,255'
}
rgb() {
return `rgb(${this.innerRGB()})`;
}
rgba(a = 1.0) {
return `rgba(${this.innerRGB()},${a})`;
}
}
const white = new Color(255, 255, 255, 'white');
const red = new Color(255, 255, 255, 'white');
white.greet();
console.log(red.greet === white.greet); //true, compare the refrences
//they are the same function because they are on the porotype
//they are not in the individual instance
define a class with the class keyword, capitalize the name
construnction function will run automatically whenever you instantiate a new instance of the class (we don't call it manually)
keyword this will refer to the individual object
assign properties to each Color (not to the prototype)
methods will added to the prototype automatically
define class and define pattern for every Color
methods look up to the one prototype template object
298. More Classes practice
When talking about OOP, we can have the Class, that is, the 'mold' that we can use to create several copies that will follow that pattern, like cake molds. Taking cakes as an analogy, each cake baked in that mold is an instance of that mold, and it will inherit its default characteristic; for the cake, it's mostly the shape, but for a Class instance, it's the default properties that are inherited, but that instance can have additional properties (the same way we can bake different cake flavors using the same mold).
299. Extends and Super keywords
class Pet {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating`;
}
}
class Cat extends Pet {
constructor(name, age, livesLeft = 9) {
//super is going to reference the class that we are extending from
//reuse functionality from construnctor
//super is referenct to the super clss
super(name, age);
this.livesLeft = livesLeft;
}
meow() {
return 'meow';
}
} //use constructor in Pet
class Dog extends Pet {
bark() {
return 'woof';
}
eat() {
return 'kung';
}
}
Author And Source
이 문제에 관하여(TIL025_210419), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@keepcalm/TIL025210419저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)