TIL014_210403
🍊 감상
호이스팅, 스코프, this, lexical this, 콜백 함수를 처음 접하고 많이 놀라버렸다...
📙 열품타 10hour
👍🏼 -
👎🏼 -
🚀 목표
- Udemy에서 Javascript 강좌 수강하기 (285/682)
- 매일 커밋 연속 30일 달성하기 (14/30, 4.03 완료)
[링크 목록]
Web Developer Bootcamp 2021
모던 자바스크립트 튜토리얼
📣 The Web Developer Bootcamp 2021: 21-7.-23-1.
21. Function
21-7. This
예시
const cat = {
name: 'Blue Steele',
color: 'gray',
breed: 'scottish fold'
meow() {
console.log(`${this.name}`);
}
}
예시
const cat = {
name: 'Blue Steele',
color: 'gray',
breed: 'scottish fold'
meow() {
console.log(`${this.name}`);
}
}
invocation context
meow2() = window.meow2() -> window 객체, 전역 객체, global object
cat.meow() -> cat 함수 안에서 불러옴
let name = 'J';
function cola () {
console.log(this.name); // console.log(window.name)과 같다
}
cola(); // 'J'
this 작동 원리 및 예시
전역 변수로 name이라는 변수 만들고 'J' 값 할당
name은 전역 변수이기에 전역 객체인 window에 속성으로 추가
-> window 객체에 name이라는 key(속성)와 'J'라는 value(값) 추가
cola라는 함수 선언, 일반 함수 실행 방식으로 실행
this는 window 객체 가르킨 것.
참고 : this에 대해서
function foo() {
console.log(this.age);
}
var age = 100;
var ken = {
age: 36,
foo: foo
}
var wan = {
age: 32,
foo: foo
}
ken.foo(); // 36
wan.foo(); // 32
var fn = ken.foo;
fn(); // 100
//출처: https://im-developer.tistory.com/96 [Code Playground]
21-8. Try & Catch
// hello is not defined
try {
hello.toUpperCase();
} catch {
console.log("ERROR")
}
try cath 안 쓰면 프로그램 자체가 실행되지 않아버림
22. Callback & Array Methods
주요 내용
forEach
map
filter
find
reducesome
every
arrow function (modern syntax)
22-1. forEach
예시
const numbers = [1,2,3,4,5]
function print(element) {
console.log(element)
}
numbers.forEach(print)
// 더 자주 쓰이는 방법, 이걸로 쓰자
const numbers = [1,2,3,4,5]
numbers.forEach(function (el) {
console.log(el)
})
// 이건 요즘의 더 새로운 방식, for을 이용해서 elment 불러오기
for (let el of numbers) {
console.log(el);
}
// 짝수만 호출하기
number.forEach(function (el) {
if (el % 2 ===0) {
console.log(el)
}
})
const movies = [
{
title: 'Amadeus',
score: 99
},
{
title: 'Stand By Me',
score: 85
}
]
movies.forEach(function(movie) {
console.log(`${movie.title} - ${movie.score}/100`)
}) //executing 이 아니라 defining임
forEach 작동원리
array 객체에서만 사용 가능한 메서드.
배열의 요소들을 반복하여 작업 수행할 수 있음.
foreach구문의 인자로 callback 함수를 등록할 수 있고, 배열의 각 요소들이 반복될 때 callback 함수가 호출된다.
callback 함수에서 배열 요소의 인덱스와 값에 접근할 수 있다
배열의 첫번째부터 마지막까지 반복하면서 item을 꺼낼 수 있다
22-2. map
예시
const texts = ['lol', 'omg', 'ttyl'];
const caps = texts.map(function (t) {
return t.toUpperCase();
})
texts; //['lol', 'omg', 'ttyl']
caps; //['LOL','OMG','TTYL']
map은 새로운 array 를 만들어서 return한다 -> 변수를 caps에 저장할 수 있음
⚠️ Exercise47) Map parctice
헤맸음
function cleanNames(arr){
const newArr = arr.map(function(str){
return str.trim();
})
return newArr;
}
// Alternative Solution
const cleanNames = arr => {
return arr.map(name => name.trim())
};
// More cleaner syntax
const cleanNames = arr => arr.map(name => name.trim());
22-3. Arrow Function
syntactically compact alternative
예시
const add = function(x,y) {
return x+y;
}
// arrow 1 two parameter
const add = (x,y) => {
return x,y;
}
add();
// If you have a signle parameter, this can be possible
const add = x => {
return x,y;
}
// rollDie, zero parameter
const rollDie = () => {
return Math.floor(Math.random()*6)+1
}
22-4. Implicit return
only do whith arrow function
예시
// with return keyword
const rollDie = () => {
return Math.floor(Math.random()*6)+1
}
// curly braces -> parenthesis, you don't have to write return keyword
// but only work in situation where there is one value and one expression
const rollDie = () => (
Math.floor(Math.random()*6)+1
)
// This can be
const add = (a,b) => {
retrun a+b;
}
// put it on one line, this is equivalent
const add = (a,b) => a+b
22-5. Arrow function wrapup
예시
//1
const newMovies = movies.map(function (movie) {
return `${movie.title} - ${movie.score / 10}`
})
//2 - with arrow function
const newMovies = movies.map(movie => (
`${movie.title} - ${movie.score / 10}`
))
22-6. setTimeout & setInterval
delay
예시
// setTimeout - wait for 3 seconds
console.log("HELLO")
setTimout() => {
console.log("Are you still there?")
},3000)
// setInterval - wait for 2 seconds - 반복함, 자주 쓰이지는 않음
setInterval(() => {
console.log(Math.random())
}, 2000)
// setInterval을 멈추는 법
const id = setInterval(() => {
console.log(Math.random())
}, 2000)
clearInterval(id);
22-7. Filter Method
예시
// making a new array, using filter, numbers는 변하지 않음
const numbers = [1,2,3,4]
numbers.filter(n => {
return n === 4
})
numbers; //[1,2,3,4]
// 높은 평점을 받은 영화만 불러오기
const goodMovies = movies.filter(movie => {
return movie.score > 80
})
// 더 간결하게
const goodMovies = movies.filter(m => m.score > 80)
const goodTitles = movies.filter.map(m => m.title)
const recentMovies = movies.filter(m => m.year > 1990)
// 높은 평점 영화의 제목만 불러오기
movies.filter(m => m.score > 80).map(m => m.title);
// v1 10자 이하 닉네임만 불러오기
const validUserNames = m => m.filter(names => names.length < 10);
//v2
const validUserNames = (strArr) => {
const filterArr = strArr.filter(names => {
return names.length < 10;
});
return filterArr;
}
//v3
function validUserNames(strArr){
const filterArr = strArr.filter(function(names) {
return names.length < 10;
});
return filterArr;
}
22-8. Some & Every Methods
filter - 새로운 array 만듦
some, every - true 랑 false 만 return
예시
const exams = [80,98,70]
//every
exams.every(score => score >= 75) //false
//some
exams.some(score => score >= 75) //true
//exercise
const allEvens = arr => arr.every(m => m%2 === 0);
22-9. Reduce Method
유용하게 쓰임
예시
//for문 사용해서
const prices = [3,5,7,9,11];
let total = 0;
for (let price of prices) {
total += price
}
console.log(total)
// array function으로
const total = prices.reduce((total, price) => {
return total+price
})
//summing an array
[3,5,7,9,11].reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
//implicit return
const total = prices.reduce((total, price) => total+price)
//가장 작은 수 찾아내기
const minPrice = prices.reduce((min.price) => {
if(price < min){
return price;
}
return min;
})
//영화
const highestRated = movies.reduce((bestMovie, currMovie) => {
if(currMovie.score>bestMovie.score) {
return currMovie;
}
return bestMovie;
})
//initial value 100으로 설정해서 100 더하기
evens.reduce((sum, num) => sum + num, 100)
23-0. ⚠️ Arrow function & this
예시
// 이건 가능함
const person = {
a: 'Viggo',
b: 'Mortensen',
fullName: function () {
return `${this.a}${this.b}`
}
}
person.fullName(); //viggo mortensen
//근데 이건 undefined undefined로 뜸, 왜?
//->arrow function doesn't have an own this value.
const person = {
a: 'Viggo',
b: 'Mortensen',
fullName: () => {
console.log(this);
return `${this.a}${this.b}`
}
}
person.fullName(); //window {......} "undefined undefined"
regular, traditional function은 함수가 만들어진 곳과는 scope되지 않는다.
function이 실행되는 곳의 영향을 받는다.
하지만 arrow function은 함수가 만들어진 곳에 scope
함수가 실행되는 곳의 영향을 받지 않는다
//window 객체 가져옴, this,fullName 에러 뜸
const person = {
a: 'Viggo',
b: 'Mortensen',
fullName: function () {
return `${this.a}${this.b}`
},
shoutName: funciton () {
setTimeout(function () {
console.log(this);
console.log(this.fullName())
}, 3000)
}
}
person.shoutName(); // window {..} this.fullName is not a function
//실행 문맥과 관련있다. setTimeout은 window의 메소드다
//arrow function으로 하면 정상적으로 작동
const person = {
a: 'Viggo',
b: 'Mortensen',
fullName: function () {
return `${this.a}${this.b}`
},
shoutName: function () {
setTimeout(() => {
console.log(this);
console.log(this.fullName())
}, 3000)
}
}
person.shoutName(); // {firstName:"Viggo", lastName:"Mortensen", ...}
// "ViggoMortensen"
23. Newer Javascript Features
23-1. Default params
추가 공부
scroll trigger
scrolling website awards
👍🏼
viewbox
svg 사용해서 container element에 fit할 수 있다. 속성 값은 네가지 넘버리스트가 주어짐. min-x min-y width height
viewBox는 svg요소가 가지는 svg의 요소가 svg요소의 viewport의 경계범위까지 확장 또는 축소, 위치지정 및 분할을 할 수 있게 해주는 속성
viewBox = "<min-x>, <min-y>, <width>, <height>"
xml
markup 언어
xml의 namespace(충돌을 막기 위한 것)
namespace에 대한 정보를 가지고 있는 페이지를 활용함
xmlns
xlink:href
css normalize
API
유튜브 api
구글 클라우드 api
구글 api 사용법
greensock scroll trigger
Author And Source
이 문제에 관하여(TIL014_210403), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@keepcalm/TIL014210403저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)