Scala, Spring-Boot, JPA를 활용한 웹 애플리케이션 개발 과정에 대해 다룬다. Spring-Boot와 JPA 조합만으로도 생산성 있는 웹 애플리케이션 개발이 가능하다. 이 조합만으로도 충분히 의미가 있지만 여기에 Scala라는 약간은 불편한 듯 보이는 언어를 도입함으로써 얻을 수 있는 즐거움을 공유한다. Spring-Boot + JPA 조합에 Scala를 적용하면서의 좌충우돌 경험담을 전한다.
NHN Forward 2018 컨퍼런스에서 발표한 자료입니다.
http://forward.nhnent.com/
MyBatis로 작성된 예제 프로그램을 JPA로 마이그레이션하는 방법에 대해 설명합니다.
cf.) https://github.com/nhnent/hands-on-labs.java.mybatis-to-jpa
NHN Forward 2018 컨퍼런스에서 발표한 자료입니다.
http://forward.nhnent.com/
MyBatis로 작성된 예제 프로그램을 JPA로 마이그레이션하는 방법에 대해 설명합니다.
cf.) https://github.com/nhnent/hands-on-labs.java.mybatis-to-jpa
탑크리에듀(www.topcredu.co.kr), 송석원 교수의 IT기술칼럼#2
자바스크립트는 ES6버전에서 class 키워드를 도입했습니다. 자바스크립트는 객체지향 언어였지만 다른 객체지향언어처럼 사용하기에는 많은 불편함이 있었습니다. 심지어 자바스크립트는 객체지향언어라고 볼 수 없다고 하는 분들도 있었을 정도였죠. 최근에 선풍적인 인기를 얻고 있는 React, Angular 같은 기술은 클래스 문법을 채택했습니다. 따라서, 클래스 문법에 대한 이해가 깊다면 새로운 기술을 습득할 때 많은 도움이 될 것 입니다.
다른 객체지향 언어와 자바스크립트의 차이를 이해하지 못하고 사용하게 되면 많은 문제점이 발생합니다. 안타깝지만 자바스크립트를 사용하고 있는 개발자들 중에서도 제대로 이해하고 사용하시는분은 많지 않은 듯 합니다.
이를 해소하기 위해서 새로 도입한 문법이 class 키워드로 대표되는 클래스 문법입니다. 객체지향 개발방법의 익숙한 개발자들을 위해서 자바스크립트가 새로운 문법을 도입한 것 입니다. 개인적으로 “JavaScript: The Good Parts”의 저자이신 Douglas Crockford 님께서 이를 어떻게 생각하는지 궁금합니다. 자바스크립트를 자바처럼 사용하는 것에 우려를 표하셨었는데, 그 사이 많은 시간이 지났으므로 입장이 바뀌었을지 궁금하군요. 선도적인 개발자들은 ES6에서 도입한 클래스 문법이 좋은 것인가 나쁜 것인가를 갖고 토론을 하기도 합니다.
입사 예정인 회사의 과제 테스트에서 제출한 자바스크립트 라이브러리입니다.
그냥 두기에는 아까워서 이렇게 공유드립니다.
본 라이브러리는 DOM Selector, Manipulation, Event 등의 기능을 제공합니다.
사용 방법은 jQuery와 동일하며, 관련 설명은 아래 프레젠테이션을 참고하시면 됩니다.
[본문] - http://youngman.kr/?p=1432
[데모] - http://test.youngman.kr/script/exam/core/
2. 1
Introduction
jQuery
. 가장 많이 사용되는 jQuery Library 의 소스 분석을 통하여 Java Script 가 지니는 Power Feature 를 설명한다
. jQuery 는 John resig 가 만든 Open Lib. 로서, 실제 Code 를 보면 간결성 과 암호화 수준의 코딩 실력에 놀라움 을 금치 못하며
본 자료를 통하여 JavaScript 를 추가로 이해 하고자 하는 목적 이다.
. jQuery 란
시스템의 내장객체 (window, document,,,) 가 기본 으로 제공하는 여러 method 나 property 를
사용자 가 간략하게 사용 하도록 macro 시킨 wrapper 이다 (이를 퍼사드 디자인 패턴이라 한다)
. jQuery Open Source
3. 2
jQuery
사용모습
.
. jQuery Event
Mouse : click, dbclick, mouseenter, mouseleave
Keyboard : keypress, keydown, keyup
Form : submit, change, blur, focus
Window/Document : load, resize, scroll, unload
사용자
Script
$(document).
ready
jQuery 선택자
jQuery
Element 객체
jQuery
Element 객체
2) Element 선택
jQuery(“selector”)
3) Event callback 등록
element.click(function F)
4) Event callback
F()
5) jQuery method 사용
element.method()
jQuery.method()
내장객체
(window,
Document,,)
및
Element 객체Event
객체생성
jQuery
1) ready() 호출
4. 3
jQuery
User Script 샘플
. Head 부분에 사용자 script 가 위치한다
. 약속 된 $(document).ready 혹은 $(function).ready 내에 함수로 scripting 한다
. $ 는 jQuery 를 의미한다, var $=jQuery=n=function(){} ;
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
// User Scripts
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
5. 4
jQuery
jQuery 구성
. 크게 보면 즉시실행함수(A) 와 A 에 arg 로 전달되는 메인 함수(B) 로 구성되어 있으며 B를 A에서 호출하는 구조이다
. B 가 실행 되면서 아래와 같은 역할이 수행된다
1) 내부에 있는 즉시실행함수 t() 의 실행 -
2) 사용자가 사용할 method 를 n.extend() 로 등록
3) 사용자가 사용할 method 를 n.fn.extend() 로 등록 , n.each() 로 등록
4) 함수 n() 에 함수 들 추가
5) jQuery 정의 (jQuery==function n()) : window.jQuery=window.$=n
!function(a,b){ // 즉시실행함수 (A)
"object"==typeof module&&"object"==typeof module.exports?
module.exports=a.document?
b(a,!0):
function(a){
if(!a.document)throw new Error("jQuery requires a window with a document");
return b(a)}:
b(a)
}("undefined"!=typeof window?window:this,
function(a,b){ // a=window , 메인함수 (B)
var n=function(a,b){ return new n.fn.init(a,b) ; }
n.fn=n.prototype={} ;
n.fn.extend=n.extend=function(){} ;
var t=function(){}() ;
n.fn.init=function(){} ;
n.extend({,,}) ;
n.fn.extend ({,,}) ;
n.each(){} ;
n.filter=function(){} ;
n(window.document) ; // document 에 대한 jQuery element 객체
var U="undefined" ;
var Kc=a.jQuery,Lc=a.$;
return n.noConflict=function(b){return a.$===n&&(a.$=Lc),b&&a.jQuery===n&&(a.jQuery=Kc),n},
typeof b===U&&(a.jQuery=a.$=n),n
});
6. 5
jQuery
내부모습
. function n 을 중심으로 구성된다
n
prototype
{}
extendfn
{}
extend
init
new n.fn.init() 사전에 만들어진 객체들
filter,Callbacks,access,acceptData
event,Event,removeEvent
swap,speed,parseJSON,parseXML
param,tween,noConflict
isWindow,isFunction,isArray,isNumeric,
isPlainObject,isEmptyObject,
type,globalEval,camelCase,nodeName,
each,trim,makeArray,inArray,merge,grep,map,proxy,now
dir,sibling,
Deffered,when
holdready,ready
hasData,data,removeData
queue,dequeue
clone,buildFragment,cleanData
cssHooks,cssNumber,style,css
attr,removeAttr
valHooks
ajaxSetup,ajax,getJSON,getScript
n.extend 로 추가된 객체들
find,filter,not,is
has,closest,index,add,addBack
data,removeData
queue,dequeue,clearQueue,promise
on,one,off,trigger,triggerHandler
text,append,prepend,before,after,remove,empty,clone,
html,replaceWith,detach,domManip
css,show,hide,toggle
fadeTo,animate,stop,finish
Attr,removeAttr
prop,removeProp
addClass,removeClass,toggleClass,hasClass
val
hover,bind,unbind,delegate,undelegate
wrapAll,wrapInner,wrap,unwrap
serialize,serializeArray
offset, position,offsetParent
n.fn.extend 로 추가된 객체들
ready,load
delay,size
parent,parents,parentsUntil,next,prev,nextAll,prevAll,
nextUntil,prevUntil,siblings,children,contents
appendTo,prependTo,insertBefore,insertAfter,replaceAll
toggle,show,hide
slideDown,slideUp,slideToggle,fadeIn,fadeOut,fadeToggle
각종 event
Ajax event
n.each 로 추가된 객체들
7. 6
jQuery
$(document).ready ()
. 즉시실행함수 n.ready.promise() 조건에 따라 timer 혹은 event 를 사용 n.extend() 로 등록된 n.ready() 를 수행
. 사용된 property
1) document.readyState
2) document.onDOMContentLoaded
3) window.onload
. $(document).ready() 는 n.ready() 가 아닌, n.fn.ready() 이다
// jQuery Code
n.fn.ready=function(a){return n.ready.promise().done(a),this}
function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}
n.ready.promise=function(b){
return H||
(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1)))
,H.promise(b)
},
n.ready.promise();
// Pratice
<script>
function myFunc(){
}
myFunc.ready=function(){document.write("aaa")};
//window.onload = myFunc.ready ; // can
//setTimeout(myFunc.ready) ; // can
document.onDOMContentLoaded = myFunc.ready ; // can't
</script>
8. 7
jQuery
$(document).ready ()
. 아래와 같은 과정을 통하여 $(document).ready() 는 n.fn.ready() 에 대한 호출임을 알 수 있다
document.write(document.nodeType) ; // 9, to remark
function n(a){
return new n.fn.init(a) ; // n.fn 을 new 하는것이다
}
n.fn=n.prototype={
m1:function(){document.write("m1")}
}
n.extend=n.fn.extend=function(a,b){ // function 추가 practice code
this[a]=b ; // this == n or n.fn
}
n.fn.ready=function(){document.write("n.fn.ready")} ;
var A=n.fn.init=function(a){ // jQuery 와 유사한 code
var temp ;
if(!a)return this;
if("string"==typeof a){} ;
return a.nodeType?
(this.context=this[0]=a,this.length=1,this):
temp=1
};
A.prototype=n.fn ; // same as n.fn.init.prototype=n.fn
n.extend("ready",function(){}) ; // n.ready 를 등록한다
window.onload = n.ready; // to call n.ready
n(document) ; // jQuery document element 객체생성
window.jQuery=window.$=n ;
$(document).ready() ; // to call n.fn.ready()
9. 8
jQuery
jQuery Method 유형
. 사용자 가 사용하는 method 는 아래와 같이 세가지로 분류된다
1) jQuery(“selector”) : n(a,b) // 선택된 element 객체 (selector) 를 return 한다
2) jQuery.method() : n.method() // n.extend() 로 등록 되어진다
3) element.method() : selector.method() // n.fn.exntend() 로 등록 되어진다
. jQuery (“selector”) 는 function n() 이며, 아래 예제와 같이 n.fn{} 을 new (instance 생성 및 상속) 하여
선택된 element 객체를 return 한다
. n.extend() 및 n.fn.extend() 를 통하여 해당 namespace 에 property (함수 및 기타) 를 추가 하며
원리는 아래 예제를 참고한다 (함수 및 객체에 동적으로 property 추가)
function n(){
}
n.fn=n.prototype={} ;
// add for function in namespace
n.extend=n.fn.extend=function(a,b){
this[a]=b ; // this == n
}
n.extend("kk",function(){document.write("kk")}) ;
n.extend("ky",function(){document.write("ky")}) ;
n.fn.extend("wk",function(){document.write("wk")}) ;
n.fn.extend("wy",function(){document.write("wy")}) ;
n.kk() ;
n.ky() ;
n.fn.wk() ;
n.fn.wy() ;
function n(){
return new n.fn.init() ; // n.fn 을 new 하는것이다
}
n.fn=n.prototype={
m1:function(){document.write("m1")}
}
var A=n.fn.init=function(){document.write("init")} ;
A.prototype=n.fn ; // same as n.fn.init.prototype=n.fn
var a=new n() ;
a.m1() ;
10. 9
jQuery
Selector
. Page (document) 내의 Element 객체 (node) 를 선택하기 위한 string 이다
. $(a[,b]) 로 expression 하며, function n(a,b) 가 호출된다, b 는 option 이다
method 설명
$(“p”) p tag 를 사용하는 전체 element
$(“#test”) ID 가 test 인 element
$(“.test”) Class 가 test 인 element
$(*) 전체 element 선택
$(this) Current HTML element 선택 (?)
$(“p.intro”) p 중 class 가 intro 인 element
$(“p:first) 첫번째 p element
$(“ul li:first”) 첫번째 ul 의 첫번쨰 li element
$(“ul li:first-child”) 모든 ul 의 첫번쨰 li element
$(“[href]”) href attribute 를 갖는 모든 element
$("a[target='_blank']") target attribute 가 blank 인 모든 a 태그를 사용하는 element
$("a[target!='_blank']") target attribute 가 blank 가 아닌 모든 a 태그를 사용하는 element
$(“:button”) input element 중 type 이 button 인 모든 element, 다른 type (radio,,,) 도 활용가능
$(“tr:even”) 짝수인 모든 tr element
$(“tr:odd”) 홀수인 모든 tr element
11. 10
jQuery
Selector
. fn.init() Instance 객체에 대한, 유사 code 를 통하여 selector 를 이해한다
var y,z=/^(?:s*(<[wW]+>)[^>]*|#([w-]*))$/ ;
function fnInit(a,b){
var c,d;
if(!a)return this;
if("string"==typeof a){
if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),
!c||!c[1]&&b){
document.write("hit1") ;
return this ;
}
if(c[1]){
document.write("hit2") ;
return this ;
}
document.write("hit3") ;
return d=document.getElementById(c[2]),
d&&d.parentNode&&(this.length=1,this[0]=d),
this.context=document,
this.selector=a,
this
}
}
var a1=new fnInit("image") ; // hit1
var a2=new fnInit("#test") ; // hit3
var a3=new fnInit(".test") ; // hit1
var a4=new fnInit("<nnnnnn>") ; // hit2
var a1=new fnInit("image") ; // hit1
12. 11
jQuery
Utility Methods
. jQuery.method() 로 호출되는 Utility method 들 에 대한 간략한 설명이다
. 주로 Array 혹은 Object Prototype 에서 기 제공하는 method 에서 제공하지 않는 조작목적 Utility 이다
method 설명
makeArray(Object) Object 을 array 로 반환한다, var a = $.makeArray(obj1)
merge(a,b) Array 를 합병해서 반환한다, newArray = $.merge([1,2,3],[4,5,6])
each (collection, callback(a,b)) 객체 혹은 array 를 지정 받아, callback 을 반복호출, a=elem(index/key), b=value
map (collection, callback(a,b)) Each 와 차이점은 callback 내의 return 조건으로 새로운 collection 탄생, newC = map()
callback 내의 a=value, b=elem(index/key)
grep(array, callback(a,b)[,invert]) 배열의 요소를 찾아 조건(함수) 에 따라 필터 한 array 를 반환한다, a=elementOfArray, b=indexInArray
inArray(a,b[,c]) 배열 내에 특정 값에 해당하는 index 를 반환한다 ,a=value, b=array, c=from index
trim(string) 양쪽 끝의 공백문자열 제거 후 반환한다
type(a) Data type 을 세부 적 으로 알 수 있다, typeof 로 알수있는 object 도 세부적으로 (array,regExp,date,,)
now() ==Date.now, 특정한 tick 값으로 반환
extend(target [,obj1][,objN]
extend([deep],target,obj1 [,objN]
객체를 합병한다
1) target 이 유일한 인자라면 jQuery 네임스페이스에 확장될 객체
2) target = obj1 + obj2 , obj1 = 기준객체, obj2=합쳐질 객체
3) deep==true 이면 깊은 수준의 합병
data
removeData
특정 element 에 object (key,value) 형식으로 data 를 추가하거나 삭제
proxy(a,b) Argument 로 pass 된 함수 (a) 의 this 를 b 로 변경한다 (call,apply)
is isFunction, isArray, isWindow, isNumeric, isPlainObject, isEmptyObject
13. 12
Function
Java Script 는 함수를 중심으로 하는 객체적 언어이다 로 정의 할 수 있다
. 함수선언 및 활용에 있어서 동적으로 Flexibility 있는 사용이 가능한 특징을 지니고 있다.
. 이를 Type Check 가 약한 특징으로 표현한다
. 다른 (C,JAVA) 언어가 사용 패턴이 정형화 되었다고 하면, Java Script 함수는 자유형에 가깝다
이런 이유로 코드의 해독이 난해한 이유가 된다
. 함수를 정의 해 보면
-. C : 특정한 기능을 갖춘 것, data 와 function 은 다른 것으로 별도의 공간에서 분리
-. Java script : data 이면서 특정한 기능을 갖춘 것, data 와 function 은 동일한 공간에서 존재.
1) 다양한 함수 선언 및 활용형태
. 무기명함수, Declaration, Expression, 자손함수, 즉시실행함수, 일반함수, 원형객체함수
2) Argument free
3) Return Type free
4) Closure 특징
5) Function Property 의 동적 확대
14. 13
Function
다양한 함수형태 의 사용
. Java Script 는 함수를 중심으로 하는 객체적 언어로 요약 할 수 있으며, 함수를 정의하는 다양한 semantic 이 존재한다
. jQuery 에서도
1) 선언함수 (function declaration) : function myFunc1(){}
2) 표현함수 (function expression) : var myFunc2 = function() {} ;
3) 자기호출함수 :
5) 익명함수
< 자기호출함수 형태>
(function (arg) {
document.write(arg, "aa") ;
})(10) ;
!function (arg) {
document.write(arg,“cc") ;
}(20) ;
var t = function(arg){
document.write(arg,“dd") ;
}(30) ;
// 아래 style 은 불가능
function (arg) {
document.write(arg,"bb") ;
}(20) ;
15. 14
Function
Channing Function
. 한 줄에 여러 객체의 method 를 호출 가능한 Java Script 의 특징이다
. 예) document.getElementbyID(“button1”).focus() 는 아래 두 가지 action 을 macro 화 한 것이다.
var x = document.getElementByID(“button1”) ;
x.foucs() ;
. jQuery(“selector”).methodX() 로 사용 하는 것도 이것을 이용하는 것이다.
. 상위객체 는 반드시 하위 객체를 return 하여야 가능하다
Obj1
method1()
Obj2
Method2()
Obj3
Method3()
method1()
return Obj2 return Obj3
method2() method3()
Obj1.method1().method2().method3()
var obj1={
m1:function(){document.write("m1");return obj2}
}
var obj2={
m2:function(){document.write("m2");return obj2},
m3:function(){document.write("m3")}
}
obj1.m1().m2() ;
obj1.m1().m3() ;
obj1.m1().m2().m3() ;
16. 15
Function
함수 및 객체에 Property 를 동적으로 추가
. Property 구성에 대한 동적인 특성을 보여준다
. jQuery 에서 주 함수인 n 에 대하여, 이것이 적용되어 있다
<예제>
function myFunc1(){
// 비워진 함수
}
// 함수에 function 추가
myFunc1.m1=function(){document.write("m1")} ;
myFunc1.m2=function(){document.write("m2")} ;
myFunc1[0]=function(){document.write(“[0]")} ;
myFunc1.[“m3”]=function(){document.write("m3")} ;
// 함수에 일반객체 추가
myFunc1.o1={
o1a:1,
o1b:function(){document.write("o1b")}
}
// 함수-일반객체 에 함수추가
myFunc1.o1.o1c = function(){document.write("o1c")} ;
myFunc1.m2() ;
myFunc1.o1.o1c() ;
function n(){
}
n.fn=n.prototype={
a:1,
b:2
}
n.prototype.c=function(){document.write("aa")} ;
n.fn.c() ; // aa
var a = new n() ;
a.c() ; // aa
17. 16
Function
함수를 data 처럼 사용
. 함수를 마치 data 처럼, argument 혹은 return 대상으로 사용한다
. 특히, 사전 정의된 함수의 함수 명 이나, var reference 를 사용하는 것이 아닌, 함수 context 자체를 사용하여 (무기명)
. Dynamic 한 함수의 활용을 기 한다
// 함수를 인자로 받아 사용
function myFunc1(arg1){
arg1() ;
arguments[0]() ;
}
myFunc1(function() {document.write("Func Arg" + "<br>")}) ;
// 함수를 return
function myFunc2(arg1){
if (arg1==1)
return function() {document.write("Func Return1" + "<br>")} ;
else if (arg1==2)
return function() {document.write("Func Return2" + "<br>")} ;
}
myFunc2(1)() ; // 함수를 return 받아 실행한다
myFunc2(2)() ; // 함수를 return 받아 실행한다
// 아래 예를 보면 data 임을 알 수 있다
function K() {}
var a = K ;
var b = function() {} ;
18. 17
Function
Argument Free
. Java 가 지원하는 overloading (argument 에 따라 여러 method 로 존재) 기능 은 없으나,
. arguments 객체를 이용하여 지정된 arguments 선언 (type, 몇 개) 없이도 Dynamic 한 사용이 가능하다
. Argument 에 객체로 전달한 경우, 하나의 객체로 처리한다
jQuery 에서 사용자 method 를 구성하는 방법
function sum(){
var result=0,
n;
for(n=0;n<arguments.length;n++){
result+=arguments[n];
}
this.result=result;
document.write(this.result + "<br>");
}
sum() ; // 0
sum(1,2,3) ; // 6
sum(1,2,3,7,8,9) ; // 30
function myFunc1(){
document.write(arguments.length + "<br>") ; // 1
document.write(typeof arguments + "<br>") ; // object
var a = arguments[0] ;
document.write(typeof a + "<br>") ; // object
a.a() ;
}
myFunc1({
a:function(){document.write("a")},
b:function(){},
c:function(){}
});
19. 18
Function
Return Type Free
. 지정된 return 선언 없이도, 어느 data type 에 대하여도 return 이 가능하다
. 특히, expression 결과를 바로 return 한다 (boolean)
주. jQuery 예 : isFunction:function(a) {return"function"===n.type(a)}
. Comma operator 와 같이 사용 : 최종 return 내용은 마지막 expression 이 된다
function myFunc1(a) {
var b=10 ;
var c=[] ; // array, typeof = object
var d={} ; // object, typeof = object
var e=function(){} ;
switch(a){
case 1:
return b ;
case 2:
return c ;
case 3:
return d ;
case 4:
return e ;
case 5:
return b==c ; // return boolean (true or false)
case 6:
return b=12 ; // return 12
}
}
document.write(typeof myFunc1(0)) ; // undefined
document.write(typeof myFunc1(1)) ; // number
document.write(typeof myFunc1(2)) ; // object
document.write(typeof myFunc1(3)) ; // object
document.write(typeof myFunc1(4)) ; // function
document.write(typeof myFunc1(5)) ; // boolean
document.write(myFunc1(6)) ; // 12
function myFunc1() {
var a=1 ;
function d(){document.write("dd")} ;
function c(){document.write("cc")} ;
return a++,d(),c(),++a ; // return 3
}
document.write(myFunc1()) ; //ddcc3
20. 19
Function
Return
. Comma operator 를 사용하는데, 이해가 안됨 – destructing assignment
function makeArray(a,b){
var c=b||[];
return null!=a&&(s(Object(a))
?n.merge(c,"string"==typeof a?[a]:a)
:f.call(c,a))
,c
}
B=function(a,b){
return a===b&&(l=!0),0
}
21. 20
Operator
특수한 Operator
. 5가지 Operator (대입, 산술, 비교, 논리, Bit ) 중 특수한 Operator 내역이다
1) === : Equal value and Equal type , dynamic data type 특징을 나타낸다
2) !== : Not Equal value or Not Equal Type
3) 논리 Operator : 논리적 and (&&), 논리적 or (||), 논리적 not (!)
4) Bitwise Operator : and (&), or (|), not (~), XOR (^), left shift (<<), right shift (>>)
5) Conditional (Ternary) : ?
function myFunc1(){
var a="abc",b="abc",c="abd" ;
var x=[] ;
if(a===b) // equal value and equal type
document.write("A" + "<br>") ;
if (a!==c) // not equal value or not equal type
document.write("B" + "<br>") ;
if (a!==x) // not equal value or not equal type
document.write("C" + "<br>") ;
}
myFunc1() ;
function myFunc1(){
var a=0,b=1,c=2 ;
var x=false;y=true,z=true ;
if(a&&b) // Not true
document.write("A" + "<br>") ;
if (b&&c) // True
document.write("B" + "<br>") ;
if (a||b) // True
document.write("C" + "<br>") ;
if(x&&y) // Not true
document.write("A" + "<br>") ;
if (y&&z) // True
document.write("B" + "<br>") ;
if (x||y) // True
document.write("C" + "<br>") ;
}
myFunc1() ;
function myFunc1(){
var a=1<<3 ;
document.write("a=" +a +"<br>") ; // a=8
var b=3<<1 ;
document.write("b=" +b +"<br>") ; // b=6
}
myFunc1() ;
22. 21
Operator
함수호출 with 논리적 Operator
. 코드 난독화 목적으로 이리 사용한 듯 하다
function myFunc1(){
document.write("aa") ;
}
function myFunc2(){
document.write("bb") ;
}
function myFunc3(){
document.write("cc") ;
}
myFunc1()||myFunc2()||myFunc3() ; // aabbcc
myFunc1()&&myFunc2()&&myFunc3() ; // aa
myFunc1()&&myFunc2()||myFunc3() ; // aacc
myFunc1()||myFunc2()&&myFunc3() ; // aabb
23. 22
Ternary Operator (?) 사용
. 일반적인 사용 (if-else) 에서 아래 추가적인 사용법이 있다
1) return 과 함께 사용
2) if-elseIf-else 도 표현가능 하다
3) Inner Ternary
function myFunc1(arg1){
var a ;
arg1>10 ? a="A" : a="B" ; //if(){} else{} , condition ? expr1 : expr2
document.write(a);
}
myFunc1(2) ; // B
function myFunc2(arg1){
var a ;
return arg1>10 ? a="A" : a="B" ; //if(){} else{} return a ;
}
var ret = myFunc2(30) ;
document.write(ret); // A
function myFunc3(arg1){
var a ;
arg1>100 ? a="A" : arg1>50 ? a="B" : a="C"; // if(){} else if() {} else{} , condition ? expr1 : condition ? Expr2 : expr3
document.write(a);
}
myFunc3(60) ; // B
!function(a,b){ // Inner Ternary
var x=1,y=2 ;
var k=1,w=2;
x==y?k==w?temp("11"):temp("12"):temp("33") ; // x==y 이면 다시 Inner tenary 를 사용
}
Operator
24. 23
Operator
Comma Operator
1) 일반적인 사용 : 변수 혹은 일반객체 내의 구성의 연속됨을 의미한다
2) 앞의 expression 에 대한 행위의 연속됨을 의미한다
. if(), if() {}, for, return 등에서 활용된다 (아래 예제 참고)
// 일반적인 사용
var aa,ab,ac,ad,ae,af ;
var obj1={a:10,b:20,c:30,d:function(){}} ;
var a=1,b=1 ;
var c,d ;
// 일반적인 nesting , { } 의 사용
if (a==b){
c=3 ;
d=3 ;
document.write(+(c+d)) ;
}
// Comma Operator 를 사용한 단순화
if (a==b)
c=4,d=4,document.write(+(c+d)) ;
// for 에서 활용
for (i=0 ; i > 32 ; i++,j++,k++)
for (i=0,j=2,k=3; i > 32 ; i++)
// if 에서 활용
//var a=1,b=1,c=3,d=3 ; // true
//var a=1,b=2,c=3,d=3 ; // true
var a=1,b=1,c=3,d=4 ; // false
if(a===b, c===d) // 마지막 c===d 만 if 조건으로 가져간다
document.write("true") ;
// return 에서 활용
function myFunc1() {
var a=1 ;
function d(){document.write("dd")} ;
function c(){document.write("cc")} ;
return a++,d(),c(),++a ; // return 3, 마지막 것을 return 한다
}
document.write(myFunc1()) ; //ddcc3
25. 24
Operator
다중 조건
. && 로 먼저 묶인다
//var a=1,b=1,c=2,d=2,e=3,f=3 ; // true
//var a=1,b=2,c=2,d=2,e=3,f=3 ; // true
//var a=1,b=1,c=2,d=3,e=3,f=3 ; // true
//var a=1,b=1,c=2,d=2,e=3,f=4 ; //true
var a=1,b=2,c=2,d=2,e=3,f=4 ; // false
if(a==b||c==d&&e==f) // == (a==b)||((c==d)&&(e==f))
document.write("true") ;
26. 25
RegExp
정규 표현식
. RegExp 는 문자들의 pattern 을 표현하는 형식이며 (“/pattern/modifier”), data type 의 객체로 취급되어 test 와 exec 메소드를 제공한다
Y=/^(?:input|select|textarea|button)$/i
Z=/^hd$/i
$=/^[^{]+{s*[native w/
_=/^(?:#([w-]+)|(w+)|.([w-]+))$/
구분 정규식 의미 사용 예
Match ^
$
.
문자열의 시작
문자열의 끝
해당 자리에 아무 문자나 올 수 있다
^ab abc,abcd,abk,abxxx
$ab ccab,dab,efgab
ab. abc,abd,ab3
Range []
()
[] 내의 형식 일치
() 묶음으로 사용
[0-9] , [a-zA-Z]
(a|b|c) a or b or c (셋중에 혼자 혹은 조합으로 아무거나 올수있다)
반복 ?
*
+
{}
바로앞에 문자가 없거나 하나만 존재 (0 or 1번)
바로앞에 문자가 없거나 하나이상 반복 (0번 이상)
바로앞에 문자가 하나이상 반복 (1번 이상)
{} 앞 문자열 (혹은 문자) 반복 개수
a?c ac,abc,bc
ab* ab,
ab+ ab,abb,abbb,abbbb
ab{2} 두개, ab{2,) 두개 이상 , ab{1,2) 한 개 혹은 두개
특수문자 d
p()
s
w
숫자를 의미
알파벳, 숫자, 알파벳/숫자 를 의미
Unicode 공백문자 (space,tab,cr)
알파벳,숫자,밑줄
D 이면 반대의미
p(Alpha) , p(Digit), p(Alnum)
S 이면 반대의미
W 이면 반대의미
27. 26
Statement
For Loop I
. Collector (Array 혹은 Plain Object) 의 element (index or key) 를 추출한다
var a=[1,2,4] ;
var b={name:"kwon",age:51,func:function(){}} ;
var c=function(){fa=4,fb=function(){}} ;
var d ;
for(d in a)
document.write(d) ; // 0,1,2
for(d in b)
document.write(d) ; // name,age,func
for(d in c) // Not hit with function
document.write(d) ;