ES5+(ETC / Function / Class / Object)

JIY00N·2023년 3월 31일
0

HTML / CSS / JavaScript

목록 보기
14/18
post-thumbnail

2023.03.31

0. 기타

  1. async vs defer : head안에 defer 쓰는 것이 가장 좋다.
<head>
  <script defer src="a.js"></script>
  <script defer src="b.js"></script>
  <script defer src="c.js"></script>
</head>
  1. 순수 바닐라JS를 사용할 때는 'use strict';를 선언하자
    ❓ 개발자들의 실수를 줄여주고, 성능 개선
  1. 호이스팅 - 어디에 선언했느냐와 상관없이 항상 젤 위로 선언을 끌어 올려주는 것
  1. boolean
    - false: 0, null, undefined, NaN, ''
    - true: any other value
  1. null vs undefined
// null
let nothing = null;
// undefined
let x;
  1. and(&&) 와 or(||) 연산자를 사용할 때 가벼운 조건부터 앞에서 쓴다
    뒤로 갈수록 heavy한 조건

1. Function

  1. scope
    밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다
  1. Early return, early exit
// bad
function upgradeUser(user){
  if(user.point > 10){
    // long upgrade logic..
  }
}
// good
function upgradeUser(user){
  if(user.point <= 10){
    return; // 조건이 아닐때만 빨리 종료
  }
  // long upgrade logic..  조건이 맞을 때 실행
}
  1. First-class function
    - functions are treated like any other value
    - can be assgined as a value to variable
    - can be passed as an argument to other functions
    - can be returned by anouther function
  1. Funtion expression - 할당된 다음부터 호출 가능
// anonymous funciton
const print = function(){
  console.log("print");
};
print(); // print
const printAgain = print;
printAgain(); // print
  1. Callback function using function expression
function randomQuiz(answer, printYes, printNo){
  if(answer === "love you"){
    printYes();
  }else{
    printNo():
  }
}
const printYes = function(){ // anonymous funciton
  console.log("yes!");
};
const printNo = function print(){ // named funciton
  console.log("No!");
};
randomQuiz("wrong", printYes, printNo); // No!
randomQuiz("love you", printYes, printNo); // Yes!
  1. Arrow Function - 항상 익명함수
const simplePrint = function(){ 
  console.log("simplePrint");
};
const simplePrint = () => console.log("simplePrint");
const add = (a,b) => a+b;
const simpleMultiply = (a,b) =>{
  //do something more
  return a*b;
};
  1. IIFE(Immediately Invoked Function Expression)
(function hello(){
  console.log("IIFE");
})(); // IIFE

2. Class

  1. 선언
class person{
  // constructor
  constructor(name, age){
    // fields
    this.name = name;
    this.age = age;
  }
  // methods
  speak(){
    console.log(`${this.name}: hello!`);
  }
}
const yoon = new Person('yoon', 25); // Object 생성
console.log(yoon.name); // yoon
console.log(yoon.age); // 25
yoon.speak(); // yoon: hello!
  1. Getter & Setters - 개발자의 실수 방지?
class User{
  constructor(firstName, lastName, age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age; // this.age는 getter를 호출, age는 setter를 호출
  }
  get age(){
    return this._age;
  }
  set age(value){
    this._age = value < 0 ? 0 : value; // 무한 반복 -> _age로 변경, 오류 방지
  }
}
const user1 = new User('hong','gildong',-1);
console.log(user1.age);
  1. Public & Private
class Experiment{
  publicField = 2; // public
  #privateField = 0; 
 // #기호를 붙이면 private, 클래스 내부에서만 사용 가능, 클래스 외부에서 값을 읽을수도 불러 올수도 없음
}
const experiment = new Experiment();
console.log(experiment.publicField); // 2
console.log(experiment.privateField); // undefined
  1. static
class Article{
  static publisher = 'Coding';
  constructor(articleNumber){
    this.articleNumber = articleNumber;
  }
  static printPublisher(){
    console.log(Article.publisher);
  }
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); // undefined
console.log(Article.publisher); // Coding
Article.printPublihser(); // Coding
  1. 상속과 다형성
// Inheritance - a way for one class to extend another class
class Shape{
  constructor(width, height, color){
  	this.width = width;
    this.height = height;
    this.color = color;
  }
  draw(){
    console.log(`drawing ${this.color} color of`);
  }
  get Area(){
    return width * this.height;
  }
}
class Rectangle extends Shape{} // 상속 extends 사용
class Triangle extends Shape{ // 다형성 예제
  draw(){
    super.draw(); // 부모의 메서드도 불러옴
    console.log('A'); // 오버라이딩
  }
  getArea(){
    return (this.width * this.height) / 2; // 오버라이딩
  }
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw(); // drawing blue color of
console.log(rectangle.getArea()); // 400
const triangle = new Triangle(20,20,'red');
triangle.draw(); // drawing red color, A
console.log(triangle.getArea()); // 200
  1. instanceOf - true or false 리턴
// 왼쪽 object가 오른쪽의 class instance인지 아닌지 확인 
console.log(rectangle instanceOf Rectangle); // true
console.log(triangle instanceOf Rectangle); // false
console.log(triangle instanceOf Triangle); // true
console.log(triangle instanceOf Shpae); // true
console.log(triangle instanceOf Object); // true
// 자바스크립트의 모든 Object는 Object를 상속함

3. Object

✔ one of the JavaScript's data types.
✔ a collection of related data and/or functionality
✔ Nearly all objects in JavaScript are instances of Object
✔ object = {key: value};

  1. literals and properties
const obj1 = {}; // Object literal
const obj2 = new Object(); // Object constructor
function print(person){
  console.log(person.name); //yoon
  console.log(person.age); // 25
}
const yoon = {name:'yoon', age:25}; // 객체
pint(yoon);
yoon.female = true; // 추가
console.log(yoon.female); // true
delete yoon.female; // 삭제
console.log(yoon.female); // undefined
  1. computed properties(계산된) - key should be always string
console.log(yoon.name); // yoon -> 코딩할 때 사용
console.log(yoon['name']); 
// yoon -> 런타임에 파라미터를 입력받아 객체 멤버에 접근할 때 사용, 
// 동적으로 key 관련 value를 받아와야할 때 사용
yoon['female']=true;
console.log(yoon.female); // true
  1. Property value shorthand
const person1 = {name:'lee', age:2};
const person2 = {name:'kim', age:3};
const person3 = {name:'park', age:4};
const person4 = new Person('yoon', 5);
console.log(person4); // {name: 'jo', age:5}
  1. Constructor Function
function Person(name, age){
  this.name = name;
  this.age = age;
}
  1. in operator - property existence check(key in obj)
console.log('name' in yoon); // true
console.log('random' in yoon); // false
  1. for...in vs for...of
// for(key in obj)
// yoon이 가지고 있는 key들이 블럭을 돌때마다 key에 할당
for(key in yoon){
  console.log(key); // name, age, female
}
// for(value of iterable) - 배열, 리스트에서 사용
const array =[1,2,4,5];
for(value of array){
  console.log(value); // 1 2 4 5
}
  1. cloning
const user = {name:'yoon', age:'25'};
const user2 = user;
user2.name = 'min';
console.log(user); // {name: 'min', age:'25'}
//old way
const user3 = {};
for(key in user){
  user3[key] = user[key];
}
console.log(user3); // {name: 'min', age:'25'};
// new way
const user4 = {};
Object.assign(user4, user);
// const user4 = Object.assign({}, user);와 동일
console.log(user4); // {name: 'min', age:'25'};
profile
블로그 이전 했습니다. https://yoon-log.vercel.app/

0개의 댓글