class Cream {
constructor() {
document.getElementsByTagName('body').innerHTML = "Creammmmmmy";
}
static hola() {}
sum() {
}
avg() {}
}
let cr = new Cream;'use strict';
function Cream() {
document.getElementsByTagName('body').innerHTML = "Creammmmmmy";
}
Cream.hola = function () {}
Cream.prototype = {
constructor: Cream,
sum: function () {},
avg: function () {}
}
let cr = new Cream;function 키워드 대신 화살표(=>)를 사용하여 간략한 방법으로 함수를 선언할 수 있다.
문법상의 차이 뿐만아니라 arrow function 내에서의 this가 function과 다름에 유의해야 한다.
- function 키워드를 사용하여 선언한 모든 함수는 prototype 속성으로 객체를 참조하지만, arrow function은 그렇지 않다.
- 따라서 생성자 함수를 arrow function으로 선언할 수 없다.
syntax
// 매개변수 지정 방법
() => { ... } // 매개변수가 없을 경우
x => { ... } // 매개변수가 한개인 경우, 소괄호를 생략할 수 있다.
(x, y) => { ... } // 매개변수가 여러개인 경우
// 함수 몸체 지정 방법
x => { return x * x } // single line block
x => x * x // 함수 몸체가 한줄의 표현식이라면 중괄호를 생략할 수 있으며 자동으로 return된다. 위 표현과 동일하다.
() => { return { a: 1 }; }
() => ({ a: 1 }) // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다.
() => { // multi line block.
const x = 10;
return x * x;
};- 함수내에서 가변 인자를 처리하기 위한 용도로 arguments 객체를 사용할 수 있다.
- arrow function 내에는 arguments 객체(모든 전달인자들을 담고있는 유사배열 객체)가 없다.
- 대신 rest parameter를 제공하는데, rest parameter는 가변 인자들을 담는 배열로서 사용할 수 있다.
syntax
const sum = (...args) => {
// console.log(arguments); // Uncaught ReferenceError: arguments is not defined
console.log(Array.isArray(args)); // args는 rest parameter로 배열이다.
args.forEach(function(item, index) {
console.log('args[' + index + '] = ' + item);
});
// args[0] = 1
// args[1] = 2
// args[2] = 3
// args[3] = 4
// args[4] = 5
};
console.log(sum(1, 2, 3, 4, 5)); // 15- function 키워드를 사용하여 선언한 함수와 arrow function 과의 큰 차이점은 this이다.
- 자신만의 this를 생성하지 않고 자신을 포함하고 있는 컨텍스트로 부터 this를 계승 받는다.
class Notification {
constructor(selector) {
if ( $.type(selector) !== 'string' ) { throw 'CSS 선택자를 전달해주세요'; }
if ( selector.trim() === '' ) { throw '빈 문자열 입니다.'; }
this.$els = $(selector);
// 전달인자로 arrow function 사용 (callback 함수)
// 해당 arrow function에서의 this는 상위 context의 this를 갖게된다.
// 상위 context의 this는 새로 만든 Notification 객체이다.
this.$els.each((i, el) => {
console.log('this :', this);
let $el = this.$els.eq(i);
// X(delete) 버튼 클릭시 .notification 요소를 삭제(notification 컨테이너 제거) 하기 위한 코드
// this.close 함수를 handler 함수로 지정할 경우 close 함수내에서 this는 (.delete) button element
// 따라서 bind 함수를 통해 context를 .notification 요소를 넘겨줌으로써
// close 함수 실행시 실행시 button이 아닌 .notification 컨테이너를 제거 할 수 있다.
$el.find('.delete').on('click', this.close.bind($el));
});
}
close() {
this.remove();
}
}
new Notification('.selector'); // 출력 : Notification {$els: m.fn.init(1)}참고
var fn = function(arg1, arg2) {
var str = '<p>aap ' + this.noot + ' ' + arg1 + ' ' + arg2 + '</p>';
document.body.innerHTML += str;
};
var context = {
'noot': 'noot'
};
var args = ['mies', 'wim'];
// 호출 될 때 'this'키워드가 false로 설정된 새 함수를 만듭니다.
// 제공된 값 앞에 주어진 인수 시퀀스가있는 제공된 값
// 새로운 함수가 호출되었을 때.
// 지원 : ECMAScript> = 5 (따라서> IE9)
var boundFn1 = fn.bind(context, args[0], args[1]);
boundFn1();
// bind()와 동일합니다.
// 지원 : jQuery 버전과 동일하며, 1.4부터 사용 가능합니다.
// 구형 브라우져에서 사용 가능
var boundFn2 = $.proxy(fn, context, args[0], args[1]);
boundFn2();.html()
- 설명 : 선택된 요소들 중에서 첫 번째 객체의 HTML 내용을 문자열로 반환하는 메소드
- return : String
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
<div class="demo-container">
<div class="demo-box2">Demonstration Box2</div>
</div>
<script>
$('demo-container').html(); // return : "<div class="demo-box">Demonstration Box</div>"
</script>.html(htmlString)
- 설명 : 인자로 받은 htmlString이 선택된 요소 내에 내용을 대체하는 메소드 (htmlString은 단순 문자가 아닌 HTML parsing 된다.)
- return : jQuery
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
<script>
$( "div.demo-container" )
.html( "<p>All new content. <em>You bet!</em></p>" );
//<div class="demo-container">
// <p>All new content. <em>You bet!</em></p>
//</div>
</script>
.html(function)
- 설명 : function(callback) 내에서 반환한 htmlString이 선택된 요소 내에 내용을 대체하는 메소드
- return : jQuery
<div class="demo-container">
<p>All new content. <em>You bet!</em></p>
<p>All new content. <em>You bet!</em></p>
<p>All new content. <em>You bet!</em></p>
</div>
<script>
$( "div.demo-container" ).html(function() {
var emphasis = "<em>" + $( "p" ).length + " paragraphs!</em>";
return "<p>All new content for " + emphasis + "</p>";
});
// <div class="demo-container">
// <p>All new content for <em>3 paragraphs!</em></p>
// </div>
</div>
</script>.animate( ) 함수는 css 속성을 제어하여 애니메이션(움직임) 효과를 만들어 냅니다.
반드시 css 속성 맵 데이터를 필요로 합니다. 이 데이터 맵은 .css( ) 함수에 인자로 사용하는 데이터 맵과 유사합니다.
-
애니메이션 속성과 값(Animation Properties and Values)
: 속성 (properties) 이란? 움직임을 만들어 낼 수 있는 css속성들- jQuery에서는 width, height, left와 같은 수치형 기능제어
- 문자열 속성인 show, hide, toggle도 사용 가능.
- 스타일 속성 값은 픽셀단위로 제어가 가능하며 em과 % 같은 값들도 가능.
- 비 스타일 속성은 scrollTop, scrollLeft 지원.
- 단, background-color는 사용이 불가합니다.
- jQuery에서 css 속성을 사용할때 명확환 속성을 사용. 예) ‘font’ x | ‘fontSize’ o || ‘font-size’ o
-
지속 시간(Duration)
: 움직임이 발생할 시간인 Duration의 기본단위는 밀리세컨드(1000분의 1초)- 높은 값을 주면 느리게 움직이고, 작은 값을 주면 빠르게 움직임 발생.
- 설정을 하지 않으면 기본값으로 400 밀리세컨드(milliseconds)가 세팅.
- fast, slow 라는 문자열로 세팅 가능.
- fast는 200 밀리세컨드, slow는 600 밀리세컨드로 기본값 세팅.
-
콜백 함수(Complete Function)
: 움직임이 완료된 다음에 해당하는 함수가 실행.- 이 콜백 함수는 인자를 가질 수 없음.
- 단, this를 사용하여 움직임이 있었던 DOM 요소를 제어 할 수 있음.
-
Step Function : .animate( ) 함수 용법 중 2번째에서 step 옵션을 줄 수 있음.
- 콜백 함수인 step 함수는 요소가 움직임일 때마다 호출되는 함수.
- 사용자 애니메이션을 구현하거나 움직임이 진행될 때마다 알림을 주는데 유용.
- 이 함수는 2개의 인자( now, fx )를 가질 수 있고, this는 움직이는 DOM 요소를 지칭.
- now : 각 스텝마다 움직임 속성에 대한 수치값
- fx
- jQuery.fx 프로토타입 객체(prototype object)의 레퍼런스
- elem 같은 속성값으로 수치데이터를 사용 가능.
- start와 end는 움직임 속성(animated property)의 처음과 끝을 나타냄.
- prop 속성은 움직이는 요소의 속성명
-
시작과 끝 효과 (Easing function) : .animate( ) 인자 중에 속도 늦추는 함수(easing function).
- jQuery에서 easing 은 기본으로 swing을 사용. swing은 끝점에 가서 속도가 살짝 느려짐. linear은 속도를 그대로 유지 시킴.
-
속성별 Easing (Pre-property Easing)
- 첫번째 인자로 속성명을 두번째 인자로 easing함수 사용 가능.
- 만약 특정 속성에 easing 함수를 정의하지 않으면 .animate( ) 함수의 easing 대표인자가 적용.
- 만일, 그 easing 인자마저도 생략하면 기본적으로 swing 함수가 사용됨.
- 설명 : 내부 자바스크립트 객체의 정확한type을 알아냅니다.
- 만약 객체가 undefined 혹은 null 값이면 그에 따라 'undefined'와 'null'값을 반환
jQuery.type(undefined) === 'undefined'
jQuery.type(null) === 'null'- 자료형이 기본값이거나 객체의 인스턴스이면 내부속성을 사용하여 유형을 결정한다.
jQuery.type( true ) === "boolean"
jQuery.type( 3 ) === "number"
jQuery.type( new Number(3) ) === "number"
jQuery.type( "test" ) === "string"
jQuery.type( new String("test") ) === "string"
jQuery.type( function(){} ) === "function"
jQuery.type( [] ) === "array"
jQuery.type( new Array() ) === "array"
jQuery.type( /test/ ) === "regexp"
jQuery.type( new Date() ) === "date"- 설명 : 해당 element에 jQuery data가 존재하는지 여부 반환
- jQuery.hasData() 메소드는 jQuery.data () 메소드에 의해 현재 저장된 임의의 값들이 있는지 결정하는 방법을 제공한다.
- element와 관련된 data가 없다면 false를 반환하고 그렇지 않으면 true를 반환한다
<p><button id="test">Test data</button></p>
<div id="data"></div>
<a id="foo" data-foo="bar" href="#">foo!</a>$.data($data, 'test', 1);
$.hasData($data); // true
$.hasData('#foo') // true참고
- jQuery API documentation : https://http://api.jquery.com/
data()의 이해
data()는 HTML 엘리먼트 내에 데이터를 저장하고 읽는 역할을 하는 함수입니다.
설명 : 해당 엘리먼트에 Javascript Type의 value를 로 저장할 수 있으며, 값으로 저장되어 있는 데이터를 읽습니다.
- 서버에서 조회된 데이터를 추후 ajax통신을 하기 위한 data 저장
- data()를 활용하여 Form의
<input>엘리먼트의 validation 적용
위의 용도 이외에도 data()는 여러방면으로 활용이 가능하며 jQuery 특성상 매우 쉽게 적용할 수 있다는 장점이 있습니다.
또한 HTML 엘리먼트에 data를 저장하기 때문에 Javascript에 data를 저장하기 위한 변수 설정이 필요없어지므로 source code를 깨끗하게 유지할 수 있으며, 2번째의 data()를 활용하면 매우 가볍고 쉽게 적용가능한 클라이언트 측 validation을 구현할 수 있습니다.
뿐만아니라 jQuery의 data()는 여타 jQuery의 API를 사용해 왔던것처럼 매우 직관적인 문법을 사용해 쉽게 배우고 적용할 수 있습니다.
[ case 1. 데이타 저장 ]
- 문법 : $(selector).data(key, value)
- key : string type의 변수로 data가 저장될 key값입니다.
- value : object type으로 JavaScript 에서 지원하는 모든 type의 데이터를 저장할수 있습니다.
<html>
<head>
<meta http-equiv="Context-Type" context="text/html;charset=UTF-8" />
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
</head>
<body>
<!-- data()가 호출되면 span엘리먼트에 "name"과 "address"가 추가됩니다.-->
<span>jQuery의 data()의 저장 방법</span>
<script type="text/javascript">
//span 엘리먼트에 data()함수로 "name"과 "address"세팅방법
$("span").data("name", "Nextree");
$("span").data("address", "가산");
</script>
</body>
</html> 위와 같이 형태로 data를 엘리먼트에 저장할 수 있습니다.
추가적으로 HTML5에서는 HTML 엘리먼트에 data-형식을 이용하여 미리 데이터를 저장할 수 있습니다. 이 방법은 jQuery의 data()를 이용해 저장한 것과 동일한 효과를 나타낼 수 있습니다.
사실 HTML5의
data-*가 나오기 전에는 개발자들마다 가지각색으로 HTML 엘리먼트에 허용되지 않는 속성(임의의 Attr속성)을 추가하여 사용했기 때문에 유지보수 측면이나 해석할때 매우 난해하고 지저분한 HTML이 많았습니다. 하지만 HTML5로 넘어오면서data-*속성이 표준화가 되면서 이전의 문제점들이 해결되었습니다.
<body>
<div>
<span
data-name='nextree'
data-address='가산'
data-member='{"name" : "김대호"}'
>.data()가 저장되는 방식</span>
</div>
</body> [ case 2. 데이터 읽기 ]
- 문법 : $(selector).data(key)
- key : 앞서 저장한 data를 읽어오기 위한 key값입니다.
- key를 생략하고 .data()으로 호출할 경우에는 해당 엘리먼트에 저장된 모든 data들이 JSON형식으로 리턴됩니다
<html>
<head>
<meta http-equiv="Context-Type" context="text/html;charset=UTF-8" />
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
</head>
<body>
<!-- data()가 호출되면 span엘리먼트에 "name"과 "address"가 추가됩니다.-->
<span>jQuery의 data()의 읽기 방법</span>
<p></p>
<p></p>
<script type="text/javascript">
$(function(){
//span 엘리먼트에 data()함수로 "name"과 "address"세팅방법
$("span").data("name", "Nextree");
$("span").data("address", "가산");
//data(Key)로 저장된 data읽기
var name = $("span").data("name");
var address = $("span").data("address");
$("p").eq(0).text(name);
$("p").eq(1).text(address);
});
</script>
</body>
</html> 위의 방법으로 저장된 data를 읽어 올 수 있습니다.
HTML5의
data-*로 저장한 경우 읽어올 경우에는"data-"를 생략한 key를 이용하여 data를 읽어올 수 있습니다.예 ) $("span").data("name");
또한 아래처럼 snake-case문법으로 저장된 데이터는 camelCase문법으로 읽어올 수 있습니다.
<span
data-member-name='김대호'
>camelCase</span>예 ) $("#span").data("memberName") ;
마찬가지로 camelCase형태의 key값으로 데이타를 저장하였다면 HTML에는 snake-case형태로 데이터가 저장됩니다.
다음은 HTML5의 data-*를 이용해 string, int, boolean, json 타입(Javascript Type)의 data들을저장하고 "==="를 이용한 비교연산을 해보았습니다.
[ html ]
<div
data-name="홍길동"
data-number="99"
data-hidden="true"
data-options='{"name":"홍길동"}'>
</div>
[ chrome console ]
자동으로 형변환된 데이터 결과
보다시피 HTML5에서는 아래의 결과처럼 "String" Type으로 저장되는 Value의 타입을 판별하여 Javascript에서 지원하는 Data Type으로 알맞게 형변환을 시켜줍니다.
[ case 3. 데이터 삭제 ]
- 문법 : $(selector).removeData(key)
- key : string type으로 삭제할 data의 key값.
아래 HTML의 첫번째 <p>엘리먼트에 동적으로 "name" data를 저장하고 removeData()를 이용하여 저장된 데이터를 삭제해 보겠습니다.
[ html ]
<body>
<p>data Name</p>
<p>data Number</p>
</body>
[ chrome console ]
보다시피 첫번째
<p>에 name이 nextree로 저장되었다가 removeData()를 이용하여 "name"으로 저장된 데이터를 삭제한 것을 확인할 수 있습니다.
이번엔 HTML5의 data-*로 미리 저장되어 있는 "name" data를 removeData()를 이용하여 삭제해보겠습니다.
[ html ]
<span
data-name='nextree'
data-address='가산'
data-mamber='{"name":"김대호"}'
></span>
[ chrome console ]
위의 결과처럼 미리 HTML에 data-*로 저장된 data들은 removeData()를 이용하여도 지워지지 않는 문제가 있습니다. 이런 경우는 .data("name", null)로 저장되어있는 값을 null로 바꿔주는것으로 해결이 가능합니다.
[참조사이트]
- [jQuery data][ http://api.jquery.com/data/ ]
- [jQuery removeData][ http://api.jquery.com/removeData/ ]
- HTML5 data-* Attributehttp://ejohn.org/blog/html-5-data-attributes/ ]
[참조사이트]
[ noti 믹스인 선언 ]
mixin noti()
.notification(class!=attributes.class)
block
button(
type="button"
aria-label="close notification"
).delete[ noti 믹스인 사용 & class 적용 ]
+noti()(class="site-noti is-primary")
+noti()(class="site-noti")
+noti()(class="site-noti is-danger")[ html로 변환된 noti 믹스인 ]
<div class="notification site-noti is-primary">
<button class="delete" type="button" aria-label="close notification"></button>
</div>
<div class="notification site-noti">
<button class="delete" type="button" aria-label="close notification"></button>
</div>
<div class="notification site-noti is-danger">
<button class="delete" type="button" aria-label="close notification"></button>
</div>[ modal 믹스인 선언 ]
mixin modal(data)
.modal(class!=attributes.class)
.modal-background
.modal-card
header.modal-card-head
h4.modal-card-title= data.title
button(type="button" aria-label="close modal").delete
section.modal-card-body
block
footer.modal-card-foot
button(type="button").button.is-success= data.success
button(type="button").button.is-cancel= data.cancel[ modal 믹스인 사용 & class적용 ]
var modal_data = {
title: 'jQuery Modal',
success: 'Save',
cancel: 'Cancel'
}
+modal(modal_data)(class="fds-modal")[ html로 변환된 modal 믹스인 ]
<div class="modal fds-modal">
<div class="modal-background"></div>
<div class="modal-card"></div>
<header class="modal-card-head">
<h4 class="modal-card-title">jQuery Modal</h4>
<button class="delete" type="button" aria-label="close modal"></button>
</header>
<section class="modal-card-body"></section>
<footer class="modal-card-foot">
<button class="button is-success" type="button">Save</button>
<button class="button is-cancel" type="button">Cancel</button>
</footer>
</div> 

