자바스크립트 / 9
- 람다표현식과 funtion()은 같지 않다
- 벡틱 ` 사용 이유 : 식에서 변수만 따로 구분하려고
- 람다식은 this를 사용할수 없다. 그래서 지역화를 하고 싶지 않을땐 람다를 쓰기도 한다
let f1 = function(){
console.log(`this.x:${this.x}`); //this x:30
}
let f2 = ()=>{
console.log("f2"); //f2문자 그대로 나온다
}
let obj = {x:30,y:50,f1,f2};
obj.f1();
obj.f2();
- window.setTimeout( ) : 일정시간 후에 코드를 실행하길 원할때 씀 (밀리세컨드 단위라서 1초가 1000)
{
let f1 = function(){
window.setTimeout(function(){
console.log("f1 타임아웃");
console.log(`this.x:${this.x}`); //this x:30
},2000); //2초 뒤에 나온다
}
let f2 = ()=>{
console.log("f2");
// console.log(`this.x:${this.x}`);
}
let obj = {x:30,y:50,f1,f2};
obj.f1();
obj.f2();
}
{
let f1 = function(){
//여기까지만 obj
window.setTimeout(function(){
console.log("타임아웃 function");
console.log(`this.x:${this.x}`); //this.x:undefined 여기는 window
},2000);
window.setTimeout(()=>{
console.log("타임아웃 arrow function");
console.log(`this.x:${this.x}`); //this.x:30
},2000);
}
let f2 = ()=>{
console.log("f2");
// console.log(`this.x:${this.x}`);
}
let obj = {x:30,y:50,f1,f2};
obj.f1();
obj.f2();
}
//funtion은 this를 갖고 있기 때문에 막혀서 언디파인디드가 나왔고
//람다는 this를 갖고 있지 않아서 밖으로 나가서 let obj = {x:30,y:50,f1,f2};을 갖게??되었다
- funtion의 this는 window객체를 참조하고 람다는 this를 가질수 없기 때문에 람다에서 this를 쓰면 오류가 난다
- apply,call,bind : 원하는걸 전달하고 싶을때 사용하는 함수
{
let f1 = function(){
console.log("==================")
console.log(this.kor,this.eng); //출력:1,2
}
f1.call({kor:1,eng:2});
}
- apply는 배열을 한번에 전달하고 call은 인자들을 전달한다
{
let f1 = function(x,y){
console.log("==================")
// console.log(this.kor);
console.log(x,y); //call을 써서,인자를 받아가지고 3,4가 나온다
}
f1.call({kor:1,eng:2},3,4);
// f1.apply({kor:1,eng:2},[3,4]);
}
- 함수가 갖고 있는 기본객체를 사용할때는 this를 사용하는게 맞다
- bind : .bind(this) 내가 전달할 객체를 this로 해달라는 의미
- 람다는 간단한 코드를 누군가에게 위임하고 싶을때 많이 쓴다. 남용하지 말기
- 스트릭트 모드(strict mode) : 코드작성시 엄격하게 관리하는 모드이다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Strict_mode
Strict mode - JavaScript | MDN
Callout: 가끔 엄격하지 않은 기본값을 " 느슨한 모드 (en-US)(sloppy mode)"라고 부르기도 합니다. 공식적인 용어는 아니지만 혹시 모르니 알아두세요.
developer.mozilla.org
- 캔버스 크기를 지정할때는 css에서 하면 안되고, html / canvas width로 하거나, js 파일에서 직접 width,height를 지정해줘야 한다
constructor(){
this.#obj = document.getElementById("canvas");
this.#obj.width = 700;
this.#obj.height = 900;
}
import Box from './box.js';
//Box와 컴포지션 관계가 됐다
export default class GameCanvas{
#obj //공개하지 않겠다
#ctx
constructor(){
this.#obj = document.getElementById("canvas");
this.#obj.width = 700; //픽셀은 안써줘도 된다. 기본값인듯? 써주면안됨XX
this.#obj.height = 500;
this.#ctx = this.#obj.getContext("2d");
this.box = new Box();
this.boy = null;
}
paint(){
this.box.draw(this.#ctx);
}
run(){ //캔버스에 생명력을 불어넣어주는..무한루프가 돌며 박스를 그린다
this.paint();
}
}