Anti Patterns
FE개발팀 김동우
doSomething();
function doSomething() {
foo1 = foo2;
...
var foo1 = 'value1';
foo3 = foo4;
...
var foo4 = 'value3';
var foo2;
}
// 함수를 사용하기 전에 선언
function avoidHoisting() {
// 함수내에서 사용하는 모든 변수를 함수 상단에서 한번에 선언
var foo1 = 'value1',
foo2,
foo3 = foo4 = 'value3';
...
}
avoidHoisting();
function voteUserChoice(votreeId, voteMode) {
var testResult = validateCheck();
var userId = ${session.userId};
if(testResult) {
var requestBodyData = {};
var voteList = [];
var votesLength = $('.vote-tab').size();
requestBodyData.votreeId = votreeId;
for (var i = 1 ; i <= votesLength; i++) {
var voteInfo = {};
var userSelectionList = [];
...
}
...
}
}
var x = 10;
function scope() {
var x = 20;
if (true) {
var x = 30;
console.log(x); // 30
}
console.log(x); // 30
}
scope();
console.log(x); // 10
function voteUserChoice(votreeId, voteMode) {
var testResult, userId,
requestBodyData, voteList, voteLength,
i, voteInfo, userSelectionList;
userId = ${session.userId};
requestBodyData, voteList,
if (testResult) {
requestBodyData = {};
voteList = [];
votesLength = $('.vote-tab').size();
requestBodyData.votreeId = votreeId;
for (i = 1 ; i <= votesLength; i++) {
voteInfo = {};
userSelectionList = [];
...
}
...
}
}
// comment_status.js
function setMemberStatus(name_path, img_path) {
var loginBtn = document.getElementById('header_login');
var img = document.getElementById('header_mem_img');
var logout = document.getElementById('logout');
var name = document.getElementById('header_name');
var div = document.getElementById("header_status_div");
div.style.visibility="visible";
loginBtn.style.visibility="hidden";
name.setAttribute("value", name_path);
img.setAttribute("src", img_path);
}
function setLogout() {
var loginBtn = document.getElementById('header_login');
var img = document.getElementById('header_mem_img');
var logout = document.getElementById('logout');
var name = document.getElementById('header_name');
var div = document.getElementById("header_status_div");
div.style.visibility="hidden";
loginBtn.style.visibility="visible";
name.setAttribute("title", " ");
img.setAttribute("src", " ");
}
<!-- main.jsp -->
<script type="text/javascript">
var $page = $('.page');
$('.menu_toggle').click(function() {
$page.toggleClass('menu_effect')
});
//interval 수정 (너무 빨리 전환됨)
$('.carousel').carousel({
interval : 30000
//changes the speed
})
...
</script>
<script type="text/javascript">
var weightList = [];
var categoryList = [];
var data = ${topKeywords };
for (var day = 1; day < 5; day++) {
var categoryObject = {
name : day + 'day ago'
};
...
</script>
function sayHello() {
var name = 'NHN';
var greeting = 'Hello!';
var message;
messge = greeting + ' My name is ' + name;
return message;
}
console.log(sayHello()); // undefined
console.log(messge); // 'Hello! My name is NHN'
console.log(window.messge); // ?
var name = 'NHN';
function hello() {
return 'Hello~';
};
console.log(window.name); // 'NHN'
console.log(window.hello()); // 'Hello~'
<!-- main.jsp -->
<script type="text/javascript">
(function() {
var $page = $('.page');
$('.menu_toggle').click(function() {
$page.toggleClass('menu_effect')
});
//interval 수정 (너무 빨리 전환됨)
$('.carousel').carousel({
interval : 30000
//changes the speed
})
...
})();
</script>
<script type="text/javascript">
(function() {
var weightList = [];
var categoryList = [];
var data = ${topKeywords };
for (var day = 1; day < 5; day++) {
var categoryObject = {
name : day + 'day ago'
};
...
})();
</script>
(function() {
var ns = tui.util.defineNamespace('basecamp.util');
/*
var ns;
window.basecamp = {};
window.basecamp.util = {};
ns = window.basecamp.util;
*/
ns.isNull = function(value) {
console.log('isNull', value);
};
ns.validate = function() {
console.log('validate!');
}
})();
basecamp.util.isNull(1); // isNull 1
basecamp.util.validate(); // validate
// AMD (require.js)
define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {
var myModule = {};
// ...
return myModule;
});
// CommonJS (browserify)
var dep1 = require('dep1');
var dep2 = require('dep2');
var myModule = {};
// ...
module.exports = myModule;
123 == "123" // true
0 == "0" // true
0 == "" // true
"" == "0" // false
0 == false // true
1 == true // true
2 == true // false
false == "false" // false
false == "0" // true
false == "" // true
false == undefined // false
false == null // false
null == undefined // true
123 === "123" // false
0 === "0" // false
0 === "" // false
"" === "0" // false
0 === false // false
1 === true // false
2 === true // false
false === "false" // false
false === "0" // false
false === "" // false
false === undefined // false
false === null // false
null === undefined // false
if (Number(strValue) === 1) {
...
}
if (String(numValue) === '10') {
...
}
var name = undefined; // X
var myObject = {
prop1: 1,
prop2: 2
};
myObject.prop2 = undefined; // X
var name;
name === undefined; // true
name === null; // false
function myFn(param1, param2) {
console.log(param1 === null); // true
console.log(param2 === undefined); // true
}
myFn(null);
var obj = {};
obj.a === undefined // true
null, undefined, boolean,
number, string, object, (symbol)
typeof null // 'object' (bug! should be null!)
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof 42 // 'number'
typeof "42" // 'string'
typeof {} // 'object'
typeof Symbol() // 'symbol' (ES6)
var name = null;
var myObject = {
prop1: 1,
prop2: 2
};
delete myObject.prop2;
function gfn_isNull(str) {
if (str == null) return true;
if (str == "NaN") return true;
if (new String(str).valueOf() == "undefined") return true;
var chkStr = new String(str);
if (chkStr.valueOf() == "undefined") return true;
if (chkStr == null) return true;
if (chkStr.toString().length == 0) return true;
return false;
}
var wrapper = new String('hello');
typeof 'hello'; // 'string'
typeof wrapper; // 'object'
wrapper === new String('hello'); // false
wrapper === 'hello'; // false
wrapper == 'hello'; // true
'hello' === 'hello' // true
'hello'.toUpperCase(); // 'HELLO';
function gfn_isNull(value) {
var str = String(value);
if (!str || str === 'null' || str === 'undefined' || str === 'NaN')
return true;
}
return false;
}
String(undefined); // 'undefined'
String(null); // 'null'
String(0/0); // 'NaN'
String(true); // 'true'
Number('123'); // 123
Number('hello'); // NaN
Boolean(1); // true
var myValue = eval("myObject." + myKey);
var data = eval('(' + jsonStr + ')');
var myValue = myObject[myKey];
var data = JSON.parse(jsonStr);
function callback() {
...
}
setTimeout('callback()', 1000);
setTimeout(callback, 1000);
//or
setTimeout(function() {
...
}, 1000);
var doSomething = new Function('param1', 'param2', 'return param1 + param2;');
// 함수 선언식 (Function statement)
function doSomething(param1, param2) {
return param1 + param2;
}
// 함수 표현식 (Function expression)
var doSomething = function(param1, param2) {
return param1 + param2;
}
function getDate(strMonth, strDay) {
var month = parseInt(strMonth); // 0
var day = parseInt(strDay); // 0
...
}
var today = getDate('08', '09');
parseInt('08', 10); // 8
parseInt('09', 10); // 9
Number('08') // 8
Number('09') // 9
for (var i = 0; i < player.length; i++) {
players[i].score++;
}
var names = [];
for (var i =0; i < player.length; i++) {
names.push(player.name);
}
players.forEach(function(player) {
player.score++;
});
var names = players.map(function(player) {
return player.name;
});
// tui.util.forEach(players, function...
// tui.util.map(players, function...
var scores = [70, 75, 80, 61, 89, 56, 77, 83, 90, 93, 66],
total = 0;
// bad
for (var i = 0; i < scores.length; i ++) {
total += scores[i];
}
// good
for (var i = 0, len = scores.length; i < len; i++) {
total += scores[i];
}
(monkey patching)
Object.prototype.getKeys = function() {
var keys = [];
for (var key in this) {
keys.push(key);
}
return keys;
}
var keys = myObject.getKeys();
if (typeof Array.prototype.map !== 'function') {
Array.prototype.map = function(f, thisArg) {
var result = [];
for (var i =0, n = this.length; i < n; i++) {
result[i] = f.call(thisArg, this[i], i);
}
return result;
};
}
function getKeys(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}
var keys = getKeys(myObject);
<div class="row">
<div class="col-sm-4">
<a href="#" onclick="oauthLogin('FACEBOOK')">
<img class="img-responsive" src="image/facebook.png"/>페이스북</a>
</div>
<div class="col-sm-4">
<a href="#" onclick="oauthLogin('TWITTER')">
<img class="img-responsive" src="image/twitter.png">트위터</a>
</div>
<div class="col-sm-4">
<a href="#" onclick="oauthLogin('PAYCO')">
<img class="img-responsive" src="image/payco.jpg">페이코</a>
</div>
</div>
<ul class="list-group">
<c:forEach items="${categoryList }" var="row">
<li class="list-group-item">
<a href="javascript:search('','${row.category_name }','${pageContext.request.contextPath}')">${row.category_name }</a>
</li>
</c:forEach>
</ul>
<div class="row">
<div class="col-sm-4">
<a href="#" class="btn-login" data-type="FACEBOOK">
<img class="img-responsive" src="image/facebook.png"/>페이스북</a>
</div>
<div class="col-sm-4">
<a href="#" class="btn-login" data-type="TWITTER">
<img class="img-responsive" src="image/twitter.png">트위터</a>
</div>
<div class="col-sm-4">
<a href="#" class="btn-login" data-type="PAYCO">
<img class="img-responsive" src="image/payco.jpg">페이코</a>
</div>
</div>
<script>
$('.btn-login').click(function(e) {
oAuthLogin($(this).data('type'));
e.preventDefault();
});
</script>
$('#graph').css("display","none");
$('#graph').empty();
$('#vote-item-image').css("visibility","hidden");
$('#vote-item-image').attr("src","");
$('#vote-item-image').css("display","none");
$('#vote-item-video').css("display","none");
$('#vote-item-video').attr("src","");
if($('#graph').css("display") == "none"){
$('#graph').css("display","inline-block");
$('#graph').empty();
if($(this).find('#vote-item-hidden-category').val() == 2){
$('#vote-item-image').css("visibility","visible");
$('#vote-item-image').attr("src",fileStorageUrl+fileName);
$('#vote-item-image').css("display","inline-block");
}
if($(this).find('#vote-item-hidden-category').val() == 3){
$('#vote-item-video').attr("src","https://www.youtube.com/embed/"+fileName);
$('#vote-item-video').css("display","inline-block");
}
}
$(".votree-box").mouseenter(function(event) {
var type = $(this).attr("value");
if(type == 2){
$(this).parents().find(".votree-hidden-form").css("display","none");
$(this).parents().find(".fa").css("display","inline");
$(this).children().css("display","none");
$(this).find("#span-title").css("display", "block");
$(this).find(".votree-hidden-form").css("display","inline");
}
});
$(".votree-box").mouseenter(function(event) {
var $this = $(this);
var type = $this.attr("value");
if(type == 2){
$this.parents().find(".votree-hidden-form").css("display","none");
$this.parents().find(".fa").css("display","inline");
$this.children().css("display","none");
$this.find("#span-title").css("display", "block");
$this.find(".votree-hidden-form").css("display","inline");
}
});
var $graph = $('#graph'),
$voteImage = $('vote-item-image'),
$voteVideo = $('vote-item-video'),
hiddenCategoryValue = $(this).find('#vote-item-hidden-category').val();
$graph.css('display', 'none').empty();
$voteImage.attr('src', '').css({
visibility: 'hidden',
display: 'none'
});
$voteVideo.attr('src', '').css('display', 'none');
if ($graph.css('display') === 'none') {
$graph.css('display', 'inline-block').empty();
if (hiddenCategoryValue === 2) {
$voateImage.attr('src', fileStorageUrl + fileName).css({
visibility: 'visible'
display: 'inline-block'
});
} else if (hiddenCategoryValue === 3) {
$voateVideo.attr('src', 'https://www.youtube.com/embed/' + fileName)
.css('display', 'inline-block');
}
}
var $graph = $('#graph'),
$voteImage = $('vote-item-image'),
$voteVideo = $('vote-item-video'),
hiddenCategoryValue = $(this).find('#vote-item-hidden-category').val();
$graph.css('display', 'none').empty();
$voteImage.attr('src', '').css({
visibility: 'hidden',
display: 'none'
});
$voteVideo.attr('src', '').css('display', 'none');
if ($graph.css('display') === 'none') {
$graph.css('display', 'inline-block').empty();
if (hiddenCategoryValue === 2) {
$voateImage.attr('src', fileStorageUrl + fileName).css({
visibility: 'visible'
display: 'inline-block'
});
} else if (hiddenCategoryValue === 3) {
$voateVideo.attr('src', 'https://www.youtube.com/embed/' + fileName)
.css('display', 'inline-block');
}
}
var $graph = $('#graph'),
$voteImage = $('vote-item-image'),
$voteVideo = $('vote-item-video'),
hiddenCategoryValue = $(this).find('#vote-item-hidden-category').val();
$graph.hide().empty();
$voteImage.attr('src', '').hide();
$voteVideo.attr('src', '').hide();
if ($graph.is(':hidden')) {
$graph.show().empty();
if (hiddenCategoryValue === 2) {
$voateImage.attr('src', fileStorageUrl + fileName).show();
} else if (hiddenCategoryValue === 3) {
$voateVideo.attr('src', 'https://www.youtube.com/embed/' + fileName).show();
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE html>
(function(){
'use strict';
...
})();
'use strict';
...
<!DOCTYPE html>
<html>
<head>
<title>HTML Page</title>
<script type="text/javascript" scr="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" scr="../js/common.js"></script>
<script type="text/javascript" scr="../js/applicationMain.js"></script>
</head>
...
<!DOCTYPE html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
...
<!-- body 요소 안, 맨 마지막에 씀 -->
<script type="text/javascript" scr="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" scr="../js/common.js"></script>
<script type="text/javascript" scr="../js/applicationMain.js"></script>
</body>
</html>
<!-- css -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/header.css">
<!-- end css -->
<!-- js -->
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="${pageContext.request.contextPath}/js/header.js"></script>
<!-- css -->
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/jquery-ui.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/header.css">
<!-- end css -->
<!-- js -->
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.js"></script>
<script src="${pageContext.request.contextPath}}/js/jquery-ui.js"></script>
<script src="${pageContext.request.contextPath}/js/header.js"></script>
function validateEmail(sEmail) {
var filter = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
if('${param.categoryCond}' != '') {
var categoryCond = '${param.categoryCond}';
} else {
var categoryCond = '';
}
$.get("<c:url value='/articles' />" + "?page=" + page
+ "&pageItem=10" + searchQuery, function(data, status) {
var totalItemCount = 1;
...
});
<script>
var articleId = ${scrap.articleId};
var scrapId = ${scrap.scrapId};
var url = "${scrap.shareUrl}";
var scrapUid = ${scrap.userId};
var userUid = ${user.userId};
</script>
<script id="data" type="application/json">// JSON String //</script>
...
<script>
var data = JSON.parse($("#data").html());
...
</script>
function createModal(data) {
var tabNum = data.subVoteList.length;
for (var i = 1; i <= tabNum; i++) {
$("#tabs").append('<li class="delete" role="presentation" id="tab' + i + '"></li>');
if (i == 1) {
var $activeTab = $("#tabs").find("#tab1");
$activeTab.addClass("active");
}
$("#tab" + i).append('<a id="vote-tab-' + i + '" href="#vote-' + i + '" aria-controls="vote-' + i + '"class="delete tabs-list" role="tab" data-toggle="tab"></a>');
$("#vote-tab-" + i).text("투표" + i);
}
for (var i = 1; i <= tabNum; i++) {
$("#voteTitle").append('<div role="tabpanel" class="delete vote-tab tab-pane" id="vote-' + i + '"></div>');
if (i == 1) {
//TODO REVIEW
var inActive = $("#voteTitle").find("#vote-1");
inActive.addClass("in active");
}
$('#vote-' + i).append('<div id ="tabC' + i + '" class="delete vote-attribute col-md-12"></div>');
$('#tabC' + i).append('<label class="delete" for="vote-topic">투표 주제</label>' + '<input type="text" value="' + data.subVoteList[i - 1].topic + '"class="delete vote-topic form-control" id="vote-name-' + i + '" disabled>' + '<label class="delete" for="vote-question">투표 항목</label>');
$('#vote-' + i).append('<div class="delete vote-attribute col-md-5 pull-right"></div>');
//Question List
//TODO REVIEW
for (var j = 1; j <= data.subVoteList[i - 1].voteItemList.length; j++) {
$('#vote-' + i).append('<div class="delete question-list" id="vote-' + i + '-attribute-' + j + '"></div>');
$('#vote-' + i + '-attribute-' + j).append('<div class="delete pull-left question-number">' + j + '</div>');
$('#vote-' + i + '-attribute-' + j).append('<div id="category' + i + '-' + j + '" class="delete vote-attribute col-md-5"></div>');
$('#category' + i + '-' + j).append('<select id="vote-' + i + '-question-type-' + j + '" class="delete vote-item-type form-control" disabled></select>');
switch (data.subVoteList[i - 1].voteItemList[j - 1].categoryId) {
case 1:
$('#vote-' + i + '-question-type-' + j).append('<option>텍스트</option>');
case 2:
$('#vote-' + i + '-question-type-' + j).append('<option>이미지</option>');
case 3:
$('#vote-' + i + '-question-type-' + j).append('<option>동영상</option>');
default:
$('#vote-' + i + '-question-type-' + j).append('<option>타입오류</option>');
}
$('#vote-' + i + '-attribute-' + j).append('<div id="inputdata' + i + '-' + j + '" class="delete vote-item-value col-md-12"></div>');
$('#inputdata' + i + '-' + j).append('<input type="text" class="delete vote-item-input form-control" id="vote-' + i + '-question-' + j + '" value="' + data.subVoteList[i - 1].voteItemList[j - 1].value + '" disabled>');
$('#vote-' + i + '-question-' + j).append('<span class="delete" id="vote-' + i + '-value-err-msg-' + j + '"></span>')
}
}
$('#sidebar-title-time').append('<label class="delete" for="votree-name">투표 이름 </label> <input type="text" class="delete form-control" id="votree-name" value="' + data.title + '">');
var startdate = new Date(data.startDatetime);
var startminutes = "0" + startdate.getMinutes();
var startseconds = "0" + startdate.getSeconds();
var formattedstartTime = startdate.getFullYear() + '-' + (('0' + (startdate.getMonth() + 1)).slice(-2)) + '-' + (('0' + (startdate.getDate())).slice(-2)) + ' ' + (('0' + startdate.getHours()).slice(-2)) + ':' + startminutes.substr(-2) + ':' + startseconds.substr(-2);
$('#sidebar-title-time').append('<label class="delete" for="start-datetime">시작 시간</label> <input class="delete" id="start-datetime" type="text" value="' + formattedstartTime + '">');
$('#sidebar-title-time').append(
'<div id="layer" class="layer delete" style="display: none;">' + '<div class="calendar-header">' + '<a href="#" class="rollover calendar-btn-prev-month">이전달</a>' + '<strong class="calendar-title"></strong>' + '<a href="#" class="rollover calendar-btn-next-month">다음달</a>' + '</div>' + '<div class="calendar-body">' + '<table cellspacing="0" cellpadding="0">' + '<thead>' + '<tr>' + '<th class="sun">S</th>' + '<th>M</th>' + '<th>T</th>' + '<th>W</th>' + '<th>T</th>' + '<th>F</th>' + '<th class="sat">S</th>' + '</tr>' + '</thead>' + '<tbody>' + '<tr class="calendar-week">' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '<td class="calendar-date"></td>' + '</tr>' + '</tbody>' + '</table>' + '</div>' + '<div class="calendar-footer">' + '<p>오늘 <em class="calendar-today"></em></p>' + '</div>'
)
var enddate = new Date(data.dueDatetime);
var endminutes = "0" + enddate.getMinutes();
var endseconds = "0" + enddate.getSeconds();
var formattedendTime = enddate.getFullYear() + '-' + (('0' + (enddate.getMonth() + 1)).slice(-2)) + '-' + ('0' + (enddate.getDate())).slice(-2) + ' ' + enddate.getHours() + ':' + endminutes.substr(-2) + ':' + endseconds.substr(-2);
$('#sidebar-title-time').append('<label class="delete" for="start-datetime">종료 시간</label> <input class="delete" id="due-datetime" type="text" value="' + formattedendTime + '">');
$('#sidebar-option').append('<li class="delete sidebar-item list-group-item" id="options">비밀 투표</li>');
$('#options').append('<div class="delete material-switch pull-right" id="sidevar-private"></div>');
if (data.plainPassword != null) {
$('#sidevar-private').append('<input class="delete" id="is-private" name="isPrivate" type="checkbox" checked />');
$('#options').append('<input type="text" class="delete form-control" id="private-password" value="' + data.plainPassword + '">');
} else {
$('#sidevar-private').append('<input id="is-private" class="delete" name="isPrivate" type="checkbox"/>');
}
$('#sidevar-private').append('<label for="is-private" class="delete label-primary"></label>');
$('#sidebar-option').append('<span class="delete" id="password-err-msg"></span>');
$('#config').append('<div class="delete vote-flexible-config"></div>');
for (var k = 1; k <= tabNum; k++) {
if (k != 1) {
$('.vote-flexible-config').append('<li id="is-duplicate-' + k + '" class="delete sidebar-item list-group-item" style="display:none" >중복투표</li>');
} else {
$('.vote-flexible-config').append('<li id="is-duplicate-' + k + '" class="delete sidebar-item list-group-item">중복투표</li>');
}
$('#is-duplicate-' + k).append('<div id = "checkbox' + k + '" class="delete material-switch pull-right"></div>');
if (data.subVoteList[k - 1].isDuplicate == 1) {
$('#checkbox' + k).append('<input class="delete label-primary" id="is-duplicate-' + k + '" name="isDuplicate" type="checkbox" checked />');
} else {
$('#checkbox' + k).append('<input class="delete label-primary" id="is-duplicate-' + k + '" name="isDuplicate" type="checkbox" />');
}
$('#checkbox' + k).append('<label class="delete label-primary" for="is-duplicate-' + k + '"></label>');
}
$('.vote-regist-tab-content').slimScroll({
height: '550px'
});
setDatetimePicker();
$('#is-private').click(function(e) {
if ($(this).is(':checked')) {
$(e.target).parent().parent().append('<input type="text" class="form-control" id="private-password">');
} else {
$('#private-password').remove();
}
$("#private-password").keypress(function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#password-err-msg").html("숫자만 가능합니다.").show().fadeOut("slow");
return false;
}
if ($(e.target).val().length > 3) {
$("#password-err-msg").html(" 4자리만 가능합니다.").show().fadeOut("slow");
return false;
}
});
});
$('.tabs-list').on('shown.bs.tab', function(e) {
var IdNum = e.target.id.substring(9);
var styleChange = $('.votree-regist-container').find("#is-duplicate-" + IdNum);
$('.vote-flexible-config .sidebar-item').hide();
styleChange.show();
});
}
(Extract Method)
function changeDivStyle(){
var sampleEl = document.getElementById('sample');
sampleEl.style.left = '200px'; // reflow 1회, repaint 1회 발생
sampleEl.style.width = '200px'; // reflow 1회, repaint 1회 발생
sampleEl.style.backgroundColor = 'blue'; // repaint 1회 발생
}
// 총 reflow 2회, repaint 3회 발생
changeDivStyle();
(특히 Repaint가 가장 큰 비용)
function changeDivStyle(){
// 한번에 모아서 할당
$('sample').css({
left: '200px',
width: '200px',
backgroundColor: 'blue'
});
}
// 총 reflow 1회, repaint 1회 발생
changeDivStyle();
if (foo)
{
bar();
}
else
{
baz();
}
if (foo) {
bar();
} else {
baz();
}
if (foo) {
bar();
}
else {
baz();
}
return
{
name: 'NHN',
project: 'basecamp'
};
return;
{
name: 'NHN',
project: 'basecamp'
};
=>
var str1 = "hi";
var str2 = 'hello';
var htmlStr1 = "<div class\"=selected\">content</div>";
var htmlStr2 = "<div class='selected'>content</div>";
var str1 = 'hi';
var str2 = 'hello';
var htmlStr = '<div class="selected">content</div>';
for (i = 1; i <= 5 ; i++) {
if (pageLength < startIdx * 5 + i )
$(".pagination").append('<li class="disabled"><a>' + (startIdx * 5 + i) +'</a></li>');
else
if ((startIdx * 5 + i) == currentPage ) {
$(".pagination").append('<li><a><strong>' + (startIdx * 5 + i) +'</strong></a></li>');
} else {
$(".pagination").append('<li><a onClick= pageNum_click('+ (startIdx * 5 + i) +') >' + (startIdx * 5 + i) +'</a></li>');
}
}
for (i = 1; i <= 5 ; i++) {
if (pageLength < startIdx * 5 + i ) {
$(".pagination").append('<li class="disabled"><a>' + (startIdx * 5 + i) +'</a></li>');
} else if ((startIdx * 5 + i) == currentPage ) {
$(".pagination").append('<li><a><strong>' + (startIdx * 5 + i) +'</strong></a></li>');
} else {
$(".pagination").append('<li><a onClick= pageNum_click('+ (startIdx * 5 + i) +') >' + (startIdx * 5 + i) +'</a></li>');
}
}
function parserTest(options) {
log('test start!!!')
(options || []).forEach(function(i) {
...
})
}
// parser는 아래와 같이 해석하고, 세미콜론을 삽입
function parserTest(options) {
log('test start!!!')(options || []).forEach(function(i) {...});
}
function parserTest(options) {
log('test start!!!');
(options || []).forEach(function(i) {
...
});
}
var MINIMUM_WIDTH = 10; // 상수명
function doSomethingImportant() {}; // 함수명
var Member = tui.util.defineClass({ // 생성자
init: function() {
this._name = null; // private 프라퍼티
},
_onClick: function() {}, // private 이벤트 핸들러
});
var firstMember = new Member();