자바스크립트
객체 자료형 (key, value)
객체는 클래스의 인스턴스다.
new String('안녕하세요');
let mystr = new String('안녕하세요');
new
는 생성자 함수를 만들어낸다. (new
를 떼면 함수가 된다.)
생성자 함수를 통해 만들어진 결과물을 인스턴스라고 부른다.
let mystr
은 지금 인스턴스를 바라보고 있다.
mystr
는 인스턴스인데 다른 말로 객체라고 부른다.
✅결론 인스턴스는 객체다.
this는 함수를 호출한 객체이다.
함수 안에 살고있다.
아래 예시를 보자.
함수를 실행했더니 콘솔에 윈도우가 찍혔다.
전역 공간의 최상위 개체인 윈도우에 선언된 것이다.
function aboutThis() {
console.log(this)
}
aboutThis();
> Window {window: Window, self: Window, document: document, name: '', location: Location, …}
전역 스코프, 블록 스코프, 함수 스코프
전역: 어디든 접근할 수 있는 공간
var myVal = "잠와죽겠어";
function myFunc() {
var myVal2 = "사람살려";
}
// 참조
myVal
> '잠와죽겠어' // 전역 스코프라서 결과값이 반환됨
myVal2
> Uncaught ReferenceError: myVal2 is not defined // 함수 스코프라서 레퍼런스 에러
at <anonymous>:1:1
let valGlobal = 'hello';
function myFunc() {
var val = "hello";
return {getVal : function() {return val}}
}
var val = 'bye';
let result = myFunc();
result
> {getVal: ƒ}
result.getVal()
> 'hello'
Math.random() // 0이상 1미만을 뽑아낸다 → 1은 절대 안나옴
> 0.8867555893762662
Math.random()*10; // 1 이상 나옴
> 3.8867829424235123
Math.floor(Math.random()*10); // 소수점 떼버림
> 8
10을 곱했더니 10 미만의 수만 나오고 있다.
곱할 값을 정해서 최댓값을 정할 수 있다.
Math.floor(Math.random()*5); // 0 ~ 5
더할 값을 정해서 최솟값을 정할 수 있다.
2부터 시작하고 싶으면 아래처럼 +2
를 해주면 된다
Math.floor(Math.random()*5+2); // 2 ~ 7
근데 +2
만 해주면 최댓값에도 +2
가 되서 원하는 값과 달라진다
원한 범위: 2 ~ 5
*5+2
해서 정해진 범위: 2 ~ 7 (0+2 ~ 5+2)
그래서 최댓값에서 최솟값을 빼줘야 한다.
Math.floor(Math.random()*(5-2)+2); // 2 ~ 5
위의 과정을 이해하면 정해진 범위에서 정수를 뱉는 랜덤함수를 만들 수 있다.
Math.floor(Math.random()*(max-min)+min);
function random(min, max) {
let result = Math.floor(Math.random()*(max-min)+min);
return result;
}
랜덤 함수 사용하기
// 랜덤 함수
function randomFunc(min, max) {
let result = Math.floor(Math.random()*(max-min)+min);
return result;
}
foreach
와 판별 변수 사용let lottoArr = [];
function lottoGenerator() {
while(lottoArr.length < 6) {
// 1 ~ 45 사이의 숫자가 result에 들어감.
let result = randomFunc(1, 46);
// 판별 변수
let isGot = false;
// 중복 판별
lottoArr.forEach(element => {
if(element === result) {
// 중복됐다고 표시!
isGot = true;
}
});
// 중복이 없다면 배열에 추가
if(!isGot) {
lottoArr.push(result);
}
}
return lottoArr;
}
// 결과값 출력
console.log(lottoGenerator());
includes
메서드 사용function lottoGenerator() {
let lottoArr = [];
while (lottoArr.length < 6) {
let result = randomFunc(1, 46);
// 중복이 없다면 배열에 추가
if(!lottoArr.includes(result)) {
lottoArr.push(result);
}
}
return lottoArr;
}
// 결과값 출력
console.log(lottoGenerator());
Set
let lottoSet = new Set();
function lottoGenerator() {
while (lottoSet.size < 6) {
let result = randomFunc(1, 46);
lottoSet.add(result);
}
return lottoSet;
}
// 결과값 출력
console.log(lottoGenerator());
DOM 은 HTML 문서의 내용을 트리형태로 구조화하여 웹페이지와 프로그래밍 언어를 연결시켜주는 역할
각각의 요소와 속성, 콘텐츠를 표현하는 단위를 '노드(node)'라고 합니다
document.querySelector();
는 css 선택자로 요소로 접근하는 것이다.
getElementById
은 해당 요소만 보여주지만 getElementsByClassName
은 class
가 가진 모든 요소의 속성을 다 가지고 와서 배열처럼 보여준다. (arrayLike, 배열 아님)
DOM 트리 접근은 최신 방식이고 효율적인 document.querySelector();
만 이용하기
버튼을 클릭하면 박스의 배경색 변경하기
btnRed.addEventListener('click', () => {
// 버튼을 클릭하면 일단 다 초기화시킴
canvas.classList.remove('red', 'yellow', 'green')
canvas.classList.add('red');
})
btnYellow.addEventListener('click', () => {
canvas.classList.remove('red', 'yellow', 'green')
canvas.classList.add('yellow');
})
btnGreen.addEventListener('click', () => {
canvas.classList.remove('red', 'yellow', 'green')
canvas.classList.add('green');
})
let btnArr = [btnRed, btnYellow, btnGreen];
btnArr.forEach((item) => {
item.addEventListener('click', () => {
// 버튼을 클릭하면 일단 다 초기화시킴
canvas.classList.remove('red', 'yellow', 'green')
// 각 버튼을 클래스이름으로 구별짓기
if(item.className === 'btn-red') {
canvas.classList.add('red');
} else if(item.className === 'btn-yellow') {
canvas.classList.add('yellow');
} else {
canvas.classList.add('green');
}
})
})
참고 링크
mdn - events 목록
new
new는 객체(인스턴스) 생성하는 연산자입니다.
ES6이전: 생성자함수와 프로토타입으로 객체지향을 구현하고 new로 객체 생성
ES6: 클래스로 객체지향을 구현하고 new로 객체 생성
프로토타입 기반 객체지향 언어
클래스가 필요 없는 객체지향 프로그래밍 언어다. ES5에서는 클래스 없이도 다음과 같이 생성자 함수와 프로토타입을 통해 객체지향 언어의 상속을 구현할 수 있다.
document.querySelector();
만 쓰는게 낫다고 하셨다! 습관 고치기222