프론트엔드스터디 e07 js namespace test debugging deferred

30
프프프프프 프프프 CH.07.Namespace, Test, Debugging, Deferred.

Upload: young-beom-rhee

Post on 07-Jan-2017

8.941 views

Category:

Engineering


7 download

TRANSCRIPT

Page 1: 프론트엔드스터디 E07 js namespace test debugging deferred

프론트엔드 스터디CH.07.Namespace, Test, Debugging, Deferred.

Page 2: 프론트엔드스터디 E07 js namespace test debugging deferred

1. 전역의 오염을 막아주는 Namespace

2. 더 나은 코드를 위한 Test, Debug-ging3. 비동기처리를 위한 Deferred, prom-ise

+@ : 유용한 것들4. 함수형 프로그래밍

Page 3: 프론트엔드스터디 E07 js namespace test debugging deferred

전역 (window object) 의 오염1. Namespace

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title> 전역의 오염 </title></head><body> <script src="../js/a.js"></script> <!-- ... 여러 개의 js 가 import ... --> <script src="../js/a2.js"></script> <script> console.dir(window); </script></body></html>

var a = 'a';var ab, ac, ad, ae;

var a = 'a2';var ab, ac2, ad2, ae;

Import 를 하는 다른 파일에서 동일한 이름의 전역변수가 있으면 Override 됨

Page 4: 프론트엔드스터디 E07 js namespace test debugging deferred

window object 에 매핑되는 것들

1. Namespace

1. 전역에 선언된 (function 안에 있지 않은 ) var 로 선언된 변수2. (“use strict” 모드가 아닌 경우 ) var 없이 선언된 모든 변수 (function 안에 선언된 경우도 해당 )3. Function expression ( 함수선언문 ) 에 사용된 모든 이름=> Javascript 의 전역은 매우 쉽게 오염된다

Page 5: 프론트엔드스터디 E07 js namespace test debugging deferred

1. Namespace

Java 의 전역

같은 이름의 변수가 전역으로 선언되어 있지만 package 이름으로 구분되어 Overriding 되지 않는다 .

Page 6: 프론트엔드스터디 E07 js namespace test debugging deferred

Packaging ( 묶기 )1. Namespace

Package 와 유사한 구조 : Object 사용

jQuery.js Underscore.js

Page 7: 프론트엔드스터디 E07 js namespace test debugging deferred

1. Namespace

전역변수 하나에 할당// 수정 전 : 전역 변수 5 개// 경고 : 안티패턴이다 .

// 생성자 함수 2 개function Parent() {}function Child() {}

// 변수 1 개var some_var = 1;

// 객체 2 개var module1 = {};module1.data = {a: 1, b: 2};var module2 = {};

// 수정 후 : 전역 변수 1 개

// 전역 객체var MYAPP = {};

// 생성자MYAPP.Parent = function () {};MYAPP.Child = function () {};

// 변수MYAPP.some_var = 1;

// 객체 컨테이너MYAPP.modules = {};

// 객체들을 컨테이너 안에 추가한다 .MYAPP.modules.module1 = {};MYAPP.modules.module1.data = {a: 1, b: 2};MYAPP.modules.module2 = {};

Page 8: 프론트엔드스터디 E07 js namespace test debugging deferred

1. Namespace범용 namespace 함수var MYAPP = MYAPP || {};

MYAPP.makeNS = function (ns_string) { var parts = ns_string.split('.'), parent = MYAPP, i; // 처음에 중복되는 전역 객체명은 제거한다 . if(parts[0] === "MYAPP") { parts = parts.slice(1); }

for (i = 0; i < parts.length; i++) { // 프로퍼티가 존재하지 않으면 생성한다 . if(typeof parent[parts[i]] === "undefined") { parent[parts[i]] = {}; }

parent = parent[parts[i]]; } return parent;};

// 반환 값을 지역 변수에 할당한다 .var module2 = MYAPP.makeNS('MYAPP.modules.module2');console.log(module2 === MYAPP.modules.module2);

// 첫부분의 'MYAPP' 을 생략하고도 쓸 수 있다 .MYAPP.makeNS('modules.module51');

// 아주 긴 네임스페이스를 만들어보자 .MYAPP.makeNS('once.upon.a.time.there.was.this.long.nested.property');

console.dir(MYAPP);

Page 9: 프론트엔드스터디 E07 js namespace test debugging deferred

1. Namespace

Private 구현var myNs;

(function () {

// 비공개 멤버 var privateName = 'foobar';

// 공개될 부분을 구현한다 . myNs = { // 특권 메서드 getName: function () { return privateName; } };})();

console.log(myNs.getName());console.log(myNs.privateName);

Closure 를 사용한다 .

Page 10: 프론트엔드스터디 E07 js namespace test debugging deferred

1. Namespace

Module 패턴var myNs = (function () {

// defined within the local scope var privateMethod1 = function () { console.log('privateMethod1 has called'); }; var privateMethod2 = function () { console.log('privateMethod2 has called'); }; var privateProperty1 = 'foobar';

return { // 외부에 공개할 메서드를 매핑한다 . publicMethod1: privateMethod1, properties:{ publicProperty1: privateProperty1 }, utils:{ publicMethod2: privateMethod2 } };})();

myNs.publicMethod1();myNs.utils.publicMethod2();console.log(myNs.properties.publicProperty1);

Page 11: 프론트엔드스터디 E07 js namespace test debugging deferred

폴더 및 파일의 구조를 객체의 구조와 맞춘다

1. Namespace

파일명과 객체를 매핑

폴더 및 파일 객체

Page 12: 프론트엔드스터디 E07 js namespace test debugging deferred

코드 ->

1. Namespace

Namespace 를 만드는 기법

Page 13: 프론트엔드스터디 E07 js namespace test debugging deferred

코드 ->

1. Namespace

Refactor-ing

Page 14: 프론트엔드스터디 E07 js namespace test debugging deferred

만들려고 하는 객체가 이미 존재하는지 여부를 체크한다 .

새로운 객체를 정의할 때 사용되는 (var 로 정의 후에 대입하는 등의 ) 로직이 전역을 오염시키지 않도록 즉시실행 함수 등의 기법을 사용한다 .

생성하는 객체의 프로퍼티에 접근 제한을 두기 원하는 경우에는 클로져를 사용한다 .

1. Namespace

주의사항

Page 15: 프론트엔드스터디 E07 js namespace test debugging deferred

Test – 좋은 테스트2. Test, Debugging

반복성 – 테스트 결과는 항상 재현 가능해야 한다 . 테스트가 반복적으로 실행되면 , 항상 정확히 같은 결과를 내야 한다 .

간결성 – 테스트는 테스트를 하는 것에만 집중해야 한다 . 테스트 코드의 의도를 훼손하지 않는 한 , 가능한 한 많은 HTML, CSS, JS 등을 제거하기 위해서 노력해야 한다 .

독립성 – 각 테스트는 독립적으로 동작해야 한다 . 테스트의 결과가 다른 테스트에 의존적이 되는 것을 피해야 한다 .

Page 16: 프론트엔드스터디 E07 js namespace test debugging deferred

Test – framework 사용비율2. Test, Debugging

Page 17: 프론트엔드스터디 E07 js namespace test debugging deferred

Qunit : jQuery 테스트 -> 범용

간결한 API

비동기 테스트 지원jQuery 를 사용하지 않은 코드도 테스트 가능특히 회귀 (regression) 테스트에 적합

2. Test, Debugging

Page 18: 프론트엔드스터디 E07 js namespace test debugging deferred

Qunit - 사용법

http://qunitjs.com/

<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>QUnit Example</title> <link rel="stylesheet" href="https://code.j-query.com/qunit/qunit-1.23.1.css"></head><body><div id="qunit"></div><div id="qunit-fixture"></div><script src="https://code.jquery.com/qunit/qunit-1.23.1.js"></script><script src="tests.js"></script></body></html>

2. Test, Debugging

Page 19: 프론트엔드스터디 E07 js namespace test debugging deferred

Qunit – assert.ok(), assert.equal()

http://qunitjs.com/cookbook/

QUnit.test( "ok test", function( assert ) { assert.ok( true, "true succeeds" ); assert.ok( "non-empty", "non-empty string succeeds" ); assert.ok( false, "false fails" ); assert.ok( 0, "0 fails" ); assert.ok( NaN, "NaN fails" ); assert.ok( "", "empty string fails" ); assert.ok( null, "null fails" ); assert.ok( undefined, "undefined fails" );});

QUnit.test( "equal test", function( assert ) { assert.equal( 0, 0, "Zero, Zero; equal succeeds" ); assert.equal( "", 0, "Empty, Zero; equal succeeds" ); assert.equal( "", "", "Empty, Empty; equal succeeds" ); assert.equal( 0, false, "Zero, false; equal succeeds" ); assert.equal( "three", 3, "Three, 3; equal fails" ); assert.equal( null, false, "null, false; equal fails" );});

2. Test, Debugging

assert.ok() : true 인지 검사 , assert.equal(a, b) : a, b 가 같은지 검사

Page 20: 프론트엔드스터디 E07 js namespace test debugging deferred

Qunit – assert.expect(), assert.async()

http://qunitjs.com/cookbook/

2. Test, Debugging

QUnit.test( "multiple call done()", function( assert ) { assert.expect( 3 ); var done = assert.async( 3 );

setTimeout(function() { assert.ok( true, "first call done." ); done(); }, 1500 );

setTimeout(function() { assert.ok( true, "second call done." ); done(); }, 1000 );

setTimeout(function() { assert.ok( true, "third call done." ); done(); }, 500 );});

비동기 테스트

Page 21: 프론트엔드스터디 E07 js namespace test debugging deferred

Qunit – 실제 코드에 적용2. Test, Debugging

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title> 도형 클래스의 모듈 테스트 </title> <link rel="stylesheet" href="https://code.jquery.-com/qunit/qunit-1.23.1.css"></head><body><!-- Qunit 테스트 결과 표시 --><div id="qunit"></div><div id="qunit-fixture"></div>

<script src="https://code.jquery.com/qunit/qunit-1.23.1.js"></script><script src="../js/common.js"></script><script src="../js/com.js"></script><script src="../js/com/yb.js"></script><script src="../js/com/yb/counterVo.js"></script><script> QUnit.test( "all object has loaded test", function( assert ) { assert.ok( com, "com has loaded"); assert.ok( com.yb, "com.yb has loaded"); assert.ok( com.yb.counterVo, "com.yb.counterVo has loaded"); });</script></body></html>

Page 22: 프론트엔드스터디 E07 js namespace test debugging deferred

Debugging – Chrome 개발자도구2. Test, Debugging

크롬 개발자도구 단축키 - F12 : 개발자 도구 열기 - Ctrl + Shift + c : element inspector - Ctrl + Shift + j : console - Ctrl + Shift + I : inspect inspector

콘솔로 확인 - console.log() : 로그 확인 - console.dir() : object 구조 확인

element inspector

Page 23: 프론트엔드스터디 E07 js namespace test debugging deferred

Debugging – Chrome 개발자도구2. Test, Debugging

break point 추가 - 코드에 debugger; - sources 탭에 직접 체크* 현재의 객체의 상태를 Watch 를 통해 실시간으로 모니터링 가능

Page 24: 프론트엔드스터디 E07 js namespace test debugging deferred

Async -> Sync

3. Deferred, Promise

비동기 처리를 순차적으로 처리해야 하는 상황이 발생비동기 A, B, C 요청을 보낸 후 모두 처리가 끝난 후에 처리비동기 A, B 요청을 보낸 후 그 결과를 사용하여 C 요청을 보내야 하는 경우 등

Page 25: 프론트엔드스터디 E07 js namespace test debugging deferred

Deferred – 처리를 지연3. Deferred, Promise

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>deferred.then demo</title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script></head><body>

<button>Filter Resolve</button><p></p>

<script> var filterResolve = function() { var defer = $.Deferred(), filtered = defer.then(function( value ) { return value * 2; }); setTimeout(function () { defer.resolve( 5 ); }, 3000); filtered.done(function( value ) { $( "p" ).html("Value is ( 2*5 = ) 10: " + value ); }); }; $( "button" ).on( "click", filterResolve );</script></body></html>

Page 26: 프론트엔드스터디 E07 js namespace test debugging deferred

$.ajax() – 비동기 통신에 사용

3. Deferred, Promise

$.when( $.ajax(), $.ajax()).done(function () { $.ajax();});

Page 27: 프론트엔드스터디 E07 js namespace test debugging deferred

코드 검증jslintjshint-> IDE 에 적용

+ @

Page 28: 프론트엔드스터디 E07 js namespace test debugging deferred

라이브러리 둘러보기jQuery, jQuery uiUnderscoreBackboneBootstrapD3

+ @

Page 29: 프론트엔드스터디 E07 js namespace test debugging deferred

참고자료- http://www.ecma-international.org/ecma-262/5.1/

- 자바스크립트 완벽 가이드 데이비드 플래너건- 자바스크립트 핵심 가이드 더글라스 크락포드- 인사이드 자바스크립트 송형주 고현준- JavaScript Patterns 스토얀 스토파노프

Page 30: 프론트엔드스터디 E07 js namespace test debugging deferred

참고자료- 자바스크립트 완벽 가이드 데이비드 플래너건- 자바스크립트 닌자 존 레식 , 베어 바이볼트- https://addyosmani.com/blog/essential-js-namespacing/#

beginners

- https://api.jquery.com

- http://api.qunitjs.com/