1) 함수선언 (Declaration)

  function school() { ... }

 

2) 함수표현 (Expression)

  var school = function() { ... }

 

3) 즉시실행 함수

   : expression 함수를 전체 괄호로 묶고, 마지막에 다시 괄호를 해준다. (보통 아래의 3가지 방식)

   : 외부로부터의 침입(?) 방지를 위해 사용되는경우가 많다.

(function speak(){ … })();
(function(a,b){ return a + b})(1,2);
((a,b) => {return a+b})(1,2);

'JavaScript' 카테고리의 다른 글

정규식  (0) 2020.12.03
Prototype  (0) 2020.12.03
Callback, Promise, Observable and Async/await  (0) 2020.12.02
this 키워드 (this, call, apply, bind and arrow function)  (0) 2020.12.01
JavaScript Object  (0) 2020.11.28

1. Callback

  : 자바스크립트에서 함수는 객체이며, 객체를 함수의 파라미터로 전달가능하기에, 즉 함수를 파라미터로 전달하는것을

   콜백함수라 하며, 함수내에서 파라미터로 전달된 함수가 먼저 실행하게끔하여 비동기에서의 취약점을 보완

  : 과거에는 많이 사용되었으나, 콜백X1000 되어 사용되는 경우가 많으며 이를 콜백지옥이라고도 표현하는데, 코드 디버

   깅, 가독성등의 문제가 발생

// 일반적인 함수
const getFriend = () => {
	return{name: "John"}
};

// 친구정보 가져오기 
const myFriend = getFriend();
console.log("My friend is ", myFriend.name);  // My friend is John


// 매 2초마다 함수실행 - 서버에서 데이터 가져오는 상황설정
const getFriend = () => {
  setTimeout(() => {
  	return {name: "John"}
  }, 2000);
};

// 데이터는 2초마다 가져오는데, 가지고 오지도 않았는데 출력하니 에러가 난다
const myFriend = getFriend();
console.log("My friend is ", myFriend.name);


// 파라미터로 cb를 넣어줌...cb는 객체이며, 이는 결국 함수이다. 
// 자바스크립트에서 함수는 객체. 
// 즉 콜백은 함수를 파라미터로 넣어서 전달하는것이며, 이를 콜백 함수라 한다
const getFriend = (cb) => {
	setTimeout(() => {
  	cb({ name: "John"});
  }, 2000);
};

// 함수를 실행할때, 익명 함수에 인자로 friend를 전달 - 함수를 파라미터로 사용
// getFriend에 파라미터를 받아서 일처리를 먼저 한 후 출력한다.  
getFriend((friend) => {
	console.log(friend.name);
})

// 확실하게 보기 위해서 아직은 헷깔리는 Arrow Function을 제거후 확인하기
function getFriend(cb){
  setTimeout(){
  	cb(name:"John"})
  }, 2000);
}

getFriend(function(friend){
	console.log(friend.name);
})

2. Promise

   : 콜백함수의 문제를 해결하고, 콜백 함수를 연결하기 위해 제시된 promise

   : 상태는 pending, fulfilled, rejected로 구분되며, then 메서드를 통해 연결한다

// Promise 예제
let myFirstPromise = new Promise((resolve, reject) => {
	setTimeout(() => {
  	resolve("Success!");
  }, 250);
});

myFirstPromise.then((successMessage) => {
	console.log("Yay! " + successMessage);
});
// Yay! Success!


// Promise 체이닝
new Promise(function(resolve, reject) {
  setTimeout(() => resolve("one"), 1000);
}).then(result => {
  console.log(result); // one
  return "two";
}).then(result => { //
  console.log(result); // two
  return "three";
}).then(function(result) {
  console.log(result); // three
}).catch(error => console.log(error.message));


// 간단한 예 추가
let promise = new Promise((resolve, reject) => {
	const button = document.querySelector('button');
  button.addEventListener('click', () => {
  	resolve(button.textContent);
  });
});

promise
  .then( (result) => {
		console.log(result);
  }).then(() => {
  	document.getElementById("res").innerHTML = "promise";
  })
  .catch(error => console.log(error.message));

3. Rxjs Observable

  : 하나 이상의 아이테을 처리할때, push 방법으로, subscribe를 통해 실현

  : observer객체는 next(), error(), complete() 함수를 가지고 있다.

const button = document.querySelector('button');
const observable = Rx.Observable.fromEvent(button, 'click');

observable.subscribe(event => {
  document.getElementById("res").innerHTML = "Observable";
	console.log(event.target);
});

4. async & await

  : 함수앞에 async, 비동기 처리되는 메서드 앞에 await

  : Promise, Callback 보다 더 뛰어난 가독성

// 기본문법
async function test() { 
  const res = await fetchUser('...'); 
  console.log(res);
}

'JavaScript' 카테고리의 다른 글

정규식  (0) 2020.12.03
Prototype  (0) 2020.12.03
즉시 실행 함수(IIFE: Immediately Invoked Function Expression)  (0) 2020.12.02
this 키워드 (this, call, apply, bind and arrow function)  (0) 2020.12.01
JavaScript Object  (0) 2020.11.28

This 키워드는 문맥에 따라 가르키는 객체가 다르며 대개 아래의 5가지 방식이 있다.

 

1) 전역객체 (Global Object)

console.log(this)  // Window { ... }
결과값은 Window{ ... } 즉 this는 글로벌 객체를 가리킨다.

2) 객체선언 (Declared Object) // 자신이 속한 함수를 포함한 가장 가까운 객체의 프로퍼티를 가리킨다

var person = {
  firstName: "Dale",
  lastName: "John",
  fullName: function() { this.firstName + ' ' + this.lastName}
 }
 person.fullName();   // Dale John

3) 객체생성(new keyword)  // constructor를 만들어서 객체생성하면 클래스처럼 재활용 가능

function Person(firstName, lastName) {
  this.firstName = firstName;  // var firstName = firstName
  this.lastName = lastName;
};
var myName = new Person('Dale', 'John');
console.log(myName);   // firstName: Dale, lastName: John

4) call, apply and bind

function add(c, d) {
  this.a = 1;
  this.b = 2;
  console.log(this.a + this.b + c + d);
}
add(3,4);  // 10
 
// What if
function add(c, d) {
  console.log(this.a + this.b + c + d);
}
add(3,4);  
// NaN 
// this.a 와 this.b 가 무엇을 가리키는지 알수 없음. 미리 만들어진 객체를 가져다 
쓸 수 있으며 아래와 같이 사용
// 만들어진 메소드 사용할때 내부에 this로 연산시
var plus = {a:1, b:2};
add.call(plus, 3, 4);     add.apply(plus, [3,4]);

// 객체내 함수 사용의 경우
var family = {
  son: 1,
  total: function(dad, mom, daughter) {
    console.log(this.son + dad + mom + daughter);
  }
}
family.total(30,26,5);  // 62  normal case

var large = { son: 2; }   // 알고보니 아들이 2살
family.total.call(large, 30, 26, 5);  // 62  call 적용

// bind - this를 가지고 있으나 실행하지 않고 있음, 파라미터의 값을 모를때 사용
// 가리키는 객체를 우선 바인드 해주는 것
var bindTest = family.total.bind(large, 40);  // large와 Dad값만 넣어둠
bindTest(36,5);  // 나머지 값도 넣어줌

5) 화살표 함수 (Arrow Function)

   - 간결한 함수를 만들어줌

   - binding 되지 않은 this

     : this값의 정의는 생성자를 통한 새로운 객체, 엄격모드에서의 undefined, 객체 메서드로서의 호출되는 경우는

      문맥의 객체로 결정됨

function Counter() {
  this.num = 0;
  this.timer = setInterval(function() {
    this.num++;  // 함수내에서의 this는 바깥에 있는 전역 객체를 가리키나 num이 존재하지 않음
    console.log(this.num);
  }, 1000);
}

// 따라서 다음과 같이 할당하여 사용
function Counter() {
  var that = this;
  that.num = 0;
  that.timer = setInterval(function() {
    that.num++;
    console.log(that.num);
  }, 1000);
}

// ECMA6 에서의 화살표 함수는 자신의 this가 없고, 바인딩한 함수를 둘러싸는 렉시컬 범위(scope)의
// this 가 사용됨. 화살표 함수의 this는 본인의 함수가 포함된 function의 this값과 동일함
function Counter() {
  this.num = 0;
  this.timer = setInterval(() => [
    this.num++;
    console.log(this.num);
  }, 1000);
}
var c = new Counter();

'JavaScript' 카테고리의 다른 글

정규식  (0) 2020.12.03
Prototype  (0) 2020.12.03
즉시 실행 함수(IIFE: Immediately Invoked Function Expression)  (0) 2020.12.02
Callback, Promise, Observable and Async/await  (0) 2020.12.02
JavaScript Object  (0) 2020.11.28

자바스크립트 객체 생성의 3가지 방법

1. 객체 리터럴

let college = {
  name = "Seneca";
  address = "1000 finch";
  course = "Programming";
};
let college = {};
college.name = "Seneca";
college.address = "1000 finch";
college.course = "Programming";

2. Object() 객체 사용

let college1 = new Object();
college1.name = "Seneca";
college1.address = "1000 finch";
college1.course = "Programming";


// Array
let arr = new Array();

3. 생성자 함수

let College = function(name, address, course){
  this.name = name;
  this.address = address;
  this.course = course;
}
let seneca = new College("Seneca York", "1000 Steeles", "CPD");
function College2(name, address, course){
  this.name = name;
  this.address = address;
  this.course = course;
}
let seneca2 = new College2("Seneca York", "1000 Steeles", "CPA");

** JSON 형태의 객체와 혼동될 수 있음

// JSON은 String Type
var person = {
  “key”: “string value”,
  “key”: number,
  “key”: true,
  “key” [‘a’,’b’,’c’]
}

// String => Object, JSON형식을 객체형식
JSON.parse(obj);

// Object => String, 객체형식을 JSON으로
JSON.stringify(obj);     // 습관적으로 마지막 fy 앞의 i를 빼먹어서 오류가 자주 발생됨

+ Recent posts