var str = "10,000";

if ( /\b(?:\d{1,3})(?:,\d{3})*(?:\.\d+)?\b/.test(str) == true ) {

    alert("천단위 수");

}

else {

    alert("천단위 수가 아닙니다.");

}


posted by 뚱2

http://easymicro.egloos.com/5488188 

http://blog.naver.com/PostView.nhn?blogId=rookieangel&logNo=140155967057  


http://www.superkts.pe.kr/helper/view.php?seq=264&PHPSESSID=5447acbb880ada74d8d967e36eac58eb 




posted by 뚱2

var str = "한글 입니다. test";

if ( /.*?[가-힣]+.*?/.test(str) == true ) {

alert("한글이 존재합니다.");

}

else {

alert("한글이 존재하지 않습니다.");

}


posted by 뚱2

// false, NaN, null, undefined, "", 0 이외의 모든것은 true 이다.

(function() {

var arr = [ false, NaN, null, undefined, "", 0 ];

for (var i = 0; i < arr.length; i++) {

if ( arr[i] ) { alert(true);  }

else          { alert(false); }

}//for (var i = 0; i < arr.length; i++) {

})();


posted by 뚱2

참고 : http://blog.naver.com/PostView.nhn?blogId=gudejrdl102&logNo=150108479957 


// IE와 타 브라우저 호환성

function handler(event) {

    var event = event || window.event;

    var target = event.target || event.srcElement;

}


posted by 뚱2

/**

 * 

 * @param interval : yyyy(년), m(월), d(일)

 * @param number : 증가 년, 월, 일

 * @param dateformat : 날짜 문자열

 * @returns {String} yyyymmdd 8자리로 리턴

 */

function DateAdd(interval, number, dateformat) {

dateformat = clear_DateSTRING(dateformat);

var int_millisecond = 1;

var int_second      = 1000 * int_millisecond;

var int_minute      = 60 * int_second;

var int_hour        = 60 * int_minute;

var int_day         = 24 * int_hour;

var YY_form = CInt(Left(dateformat, 4));

var MM_form = CInt(Mid(dateformat, 5, 2))-1;

var DD_form = CInt(Right(dateformat, 2));

var date = new Date(YY_form, MM_form, DD_form);

var date_milliseconds = date.valueOf();

var add_milliseconds  = 0;

var ret_date = null;

switch (interval) {

case "yyyy":

date.setFullYear(date.getFullYear()+number, date.getMonth(), date.getDate());

ret_date = date;

break;

case "m":

date.setFullYear(date.getFullYear(), date.getMonth()+number, date.getDate());

ret_date = date;

break;

case "d":

add_milliseconds  = number * int_day;

ret_date = new Date(date_milliseconds + add_milliseconds);

break;

}

var year  = ret_date.getFullYear();

var month = ret_date.getMonth() + 1;

if ( month < 10 ) {

month = "0" + month;

}

var day   = ret_date.getDate();

if ( day < 10 ) {

day = "0" + day;

}

return ( "" + year + month + day );

}


posted by 뚱2

출처 : http://www.w3schools.com 

The JavaScript global properties and functions can be used with all the built-in JavaScript objects.


JavaScript Global Properties

PropertyDescription
InfinityA numeric value that represents positive/negative infinity
NaN"Not-a-Number" value
undefinedIndicates that a variable has not been assigned a value

JavaScript Global Functions

FunctionDescription
decodeURI()Decodes a URI
decodeURIComponent()Decodes a URI component
encodeURI()Encodes a URI
encodeURIComponent()Encodes a URI component
escape()Encodes a string
eval()Evaluates a string and executes it as if it was script code
isFinite()Determines whether a value is a finite, legal number
isNaN()Determines whether a value is an illegal number
Number()Converts an object's value to a number
parseFloat()Parses a string and returns a floating point number
parseInt()Parses a string and returns an integer
String()Converts an object's value to a string
unescape()Decodes an encoded string


posted by 뚱2

링크 : http://firejune.com/1275/자바스크립트+메모리+릭+디텍터?stag=메모리+릭 

링크 : http://rhio.tistory.com/177



JSLeaksDetector.msi


posted by 뚱2
자바의 import와 비슷하게 패키지 명을 입력해서 인클루드 하게 만들었습니다.

/**

* url은 문자열 배열이나 문자열이 올수 있다.

* 예) "SEED.df.DF_01.DF_HEADER_SEL"

*     ["SEED.df.DF_01.DF_HEADER_SEL", "SEED.df.DF_01.DF_HEADER"]

*/

SEED.importScript = function(url) {

var urls = [];

if ( url == undefined || url == null || url == "" ) {

return;

}

if ( $.type(url) == "string" ) {

urls.push(url);

}

else if ( $.type(url) == "array" ) {

urls = url;

}

else {

return;

}

$.each(urls, function(index, el) {

var newUrl = el.replace(/(^SEED\.)/gi, ""); // SEED가 있다면 제거한다. 

newUrl = newUrl.replace(/\./g, "/") + ".js";

var fullUrl = SEED.contextPath.get() + "/resources/js/" + newUrl;

$script = $("<script type=\"text/javascript\" charset=\"utf-8\" src=\"" + fullUrl + "\"></script>");

$script.bind("readystatechange", function() {

var $this = $(this);

if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

// FIXME : 나중에 메모리가 세는지 꼭 검사해야 한다.

// Handle memory leak in IE

this.onload = this.onreadystatechange = null;

$this.remove();

}

});

$script.appendTo("body");

});

};


posted by 뚱2

한글주소를 URL뒤에 붙이는 쿼리 스트링으로 전달하면 깨지는 경우가 발생합니다.

이럴때는 인코딩을 해줘야 합니다.



참고 : http://www.w3schools.com/jsref/jsref_obj_global.asp


위에서


FunctionDescription
decodeURI()Decodes a URI
decodeURIComponent()Decodes a URI component
encodeURI()Encodes a URI
encodeURIComponent()Encodes a URI component
escape()Encodes a string


함수를 이용하시면 됩니다.

posted by 뚱2

자바스크립트는 선언되지 않는 변수에 값을 할당하면은 자동적으로 글로벌에 생성됩니다.

 

다만 선언되지 않은 변수를 사용하면 런타임에러가 발생합니다.

 

그리고 정의 되었지만 값을 할당한 적이 없는 경우는 undefined가 리턴됩니다.

 

또한 객체의 정의되지 않는 property를 읽을때도 undefined가 리턴됩니다.

 

참고 : 자바스크립트 완벽 가이드

// 현재 값은 undefined
var no_init; 
// 선언되지 않은 변수를 사용했기 때문에 에러가 발생
alert(u); 
//선언되지 않은 변수에 값을 할당하려 하는 순간 이 변수가 생성된다.
u = 3;

posted by 뚱2

링크 : http://luvstudy.tistory.com/13 

posted by 뚱2

[Javascript] DateAdd

JavaScript/JavaScript 2012. 7. 14. 22:22
// 예 add_DATEs("2012-12-31", 3) 이면 2013-01-03을 리턴
function add_DATEs(dateformat, dates) {
	dateformat = clear_DateSTRING(dateformat);
	var int_millisecond = 1;
	var int_second      = 1000 * int_millisecond;
	var int_minute      = 60 * int_second;
	var int_hour        = 60 * int_minute;
	var int_day         = 24 * int_hour;
	
	var YY_form = CInt(Left(dateformat, 4));
	var MM_form = CInt(Mid(dateformat, 5, 2))-1;
	var DD_form = CInt(Right(dateformat, 2));
	
	var date = new Date(YY_form, MM_form, DD_form);
	var date_milliseconds = date.valueOf();
	var add_milliseconds  = dates * int_day;
	var ret_date = new Date(date_milliseconds + add_milliseconds);
	
	var year  = ret_date.getFullYear();
	var month = ret_date.getMonth() + 1;
	if ( month < 10 ) {
		month = "0" + month;
	}
	var day   = ret_date.getDate();
	if ( day < 10 ) {
		day = "0" + day;
	}
	
	return ( "" + year + month + day );
}
posted by 뚱2

참고 : http://codemuri.tistory.com/756 

자바스크립트는 기본적으로 탐욕적 수량자이다.


1. 탐욕적 수량자와 게으른 수량자


 탐욕적 수량자게으른 수량자 
 * *? 
 + +? 
 {n,} {n,}? 

posted by 뚱2

참조 : JavaScript Patterns 에서 발췌


//=======================================================================
// SEED Class 영역
//=======================================================================
var SEED = SEED || {};

/**
 * 네임스페이스를 생성한다.
 * @param ns_string
 */
SEED.ns = function(ns_string) {
	var parts = ns_string.split("."),
		parent = SEED,
		i;
	
	// 처음에 중복되는 전역 객체명은 제거한다.
	if ( parts[0] === "SEED" ) {
		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 = SEED.ns("SEED.modules.modules2");
module2 === SEED.modules.module2;//true

posted by 뚱2

/**

 * obj  : url or json data

 * data : json data

 */

my.submitWithJson = function(obj, data, target, method) {

    try {

        var param = null;       

        // json object이라면

        if ( obj && Object.prototype.toString.call(obj) === '[object Object]' ) {

            param = {

                 'url'     : obj.url                 || ''

                ,'data'    : obj.data                || {}

                ,'target'  : obj.target              || '_self'

                ,'method'  : obj.method              || 'POST'

            };

        }

        else {

            param = {

                 'url'     : obj                     || ''

                ,'data'    : data                    || {}

                ,'target'  : target                  || '_self'

                ,'method'  : method                  || 'POST'

            }; 

        }

         

        //랜덤한 수를 출력

        var curDate   = new Date();

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

            strId += param.target;

            strId += "_";           

            strId += curDate.getFullYear();

            strId += curDate.getMonth();

            strId += curDate.getDay();

            strId += curDate.getHours();

            strId += curDate.getMinutes();

            strId += curDate.getSeconds();

            strId += "_" + ranNumber;

             

        var $newForm = jQuery("<form></form>")

                        .attr("name"  , strId)

                        .attr("id"    , strId)

                        .attr("method", param.method);

        if ( $newForm ) {

            if ( Object.prototype.toString.call(param.data) === "[object Array]") {

                jQuery.each(param.data, function(index, val) {

                    var row = val;

                    jQuery.each(row, function(key, val) { 

                        jQuery("<input type='"hidden"'>")

                            .attr("name" , key)

                            .attr("value", val)

                            .appendTo($newForm);

                    });

                });

                $newForm.appendTo(document.body);

            }

            else {

                jQuery.each(param.data, function(key, val) { 

                    jQuery("<input type='"hidden"'>")

                        .attr("name" , key)

                        .attr("id"   , key)

                        .attr("value", val)

                        .appendTo($newForm);

                });

                $newForm.appendTo(document.body);               

            }

     

            var myForm = $newForm[0];

            myForm.action = param.url;

            myForm.method = param.method;

            myForm.target = param.target;

             

            myForm.submit();

            $newForm.remove();

        }//if ( $popForm ) {

    }

    catch (e) {alert(e.message);}

    finally   {}

}; 


posted by 뚱2
var str = "<span id ='' />";
// 변경할 문자가 브라우져가 인식해서 할수 없이 띄어쓰기를 했다.
// 실제 변경할때는 변경할 문자들 사이에 공백이 없어야 한다.
str.replace(/<(\/?[a-zA-Z]+?.*?\/?)>/gmi, "& l t ; $1 & g t ;");

posted by 뚱2
참고 : 자바스크립트 완벽가이드 (JavaScript The Definitive Guide 5/E)

i : 대소문자를 구별하지 않는 매칭을 수행한다.
g : 전역 매칭을 수행한다. 즉, 첫 번째 매치에서 끝내지 않고 매치되는 모든 것을 찾는다.
m : 여러 줄 상태 ^는 줄의 시작이나 문자열의 시작에 매치되고, $는 줄의 끝이나 문자열의 끝에 매치된다.

1. search()
   이 메서드는 정규 표현식을 전달인자로 받아서 가장 처음 매칭되는 부분 문자열의 위치를 반환하고
   , 매칭되는 부분 문자열이 없다면 -1을 반환한다.
   * 정규표현식에서 g 플래그가 있으면 무시한다.

2. replace()
   이 메서드는 찾아서 바꾸기 작업을 수행한다.
   * 정규 표현식에 g 플래그가 설정되어 있으면 문자열내에서 패턴에 매치되는 무든 부분 문자열을 교체할 문자열로 바꾼다.
   * 정규 표현식에서 괄호로 묶인 부분 표현식은 왼쪽에서 오른쪽으로 번호가 매겨지고, 각 부분 표현식과 매치된 텍스트를 기억한다.
      만약 교체할 문자열에 $가 나오고 뒤따라 숫자가 나타나면 replace() 메서드는 $와 숫자를 부분 문자열에 매치된 텍스트로 바꾼다.

3. match()
    이 메서드는 정규 표현식을 유일한 전달인자로 받고 매치된 결과를 배열로 만들어 반환한다.
    , 매칭되는 부분 문자열이 없다면 null을 반환한다.


posted by 뚱2
var parent = {
	 method1 : function() {
	 }
};

var child = (function(parentObj) {
    var F = function(){
        this.method2 = function() {
        };
    };
    F.prototype = parentObj;
    return (new F());
})(parent);

console.log("method1" in child);// true
console.log("method2" in child);// true
console.log(child.hasOwnProperty("method1") );// false
console.log(child.hasOwnProperty("method2") );//true

초 간단 샘플예제이다.
객체에  메소드가 존재하는지 확인하는 방법은 hasOwnProperty 메소드와 in 연산자로 확인할수 있다.
다만 hasOwnProperty는 객체 자신의 메소드 인지 확인하는 것이고
in 연산자는 상속계통을 다 뒤져서 존재하는지 확인하는 메소드 이다.
posted by 뚱2

arguments.callee

This property is a reference to the function that you are in. Which is very handy if you want to get a reference to an anonymous function from inside itself. One good reason for doing this would be in a recursive anonymous function.

arguments.caller

This property is a reference to the function that called the function you are in. This allows you to get access to the entire current callstack which is very handy for debugging.


function test() {
    console.log(">>>test");
    console.log("arguments.callee\n" + arguments.callee);
    console.log("arguments.caller\n" + arguments.caller);
    console.log("arguments.callee.caller\n" + arguments.callee.caller);
    test1();
}

function test1() {
    console.log(">>>test1");
    console.log("arguments.callee\n" + arguments.callee);
    console.log("arguments.caller\n" + arguments.caller);
    console.log("arguments.callee.caller\n" + arguments.callee.caller);        
}    
test();

//  로그기록
//>>>test
//arguments.callee 
//function test() { 
//    console.log(">>>test"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//    test1(); 
//}
//arguments.caller undefined
//arguments.callee.caller null
//>>>test1
//arguments.callee 
//function test1() { 
//    console.log(">>>test1"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//}
//arguments.caller undefined
//arguments.callee.caller 
//function test() { 
//    console.log(">>>test"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//    test1(); 
//}

위와 같이 오출하면 로그(firefox)이 찍힌다.
결국 arguments.callee 는 함수의 입장에서 자기자신
arguments.callee.caller 는 arguments.callee를 호출한 함수이다.
호출한 쪽이 함수가 아니라 전역환경이라면
arguments.callee.caller null 이다.
arguments.callee는 익명함수의 재귀호출에 유용하다.

* 추가적으로 callee, caller가 null이거나 undefined가 아닐때
Object.prototype.toString.call(arguments.callee);
Object.prototype.toString.call(arguments.callee.caller);
호출해 보면은 둘다 [object Function]을 리턴하는것을 알수 있다.


posted by 뚱2
jQuery를 이용해서 만들었다.
기본적으로 jQuery를 임포트 해야 한다.

var myStringify = function(data) {
    var  msg           = ""
        ,myData        = data || {}
        ,mySection     = ","
        ,isData        = false
        ,dataType      = jQuery.type(myData)
        ;
          
    // 배열인지 검사
    if ( dataType == "array" ) {
        msg += "[";
    }
    else if ( dataType == "object" ) {
        msg += "{";
    }
      
    jQuery.each(myData, function(k, v) {
        isData = true;
        var propertyType = jQuery.type(v);
         
        if ( propertyType == "array" || propertyType == "object" ) {
            if ( dataType == "array" ) {
                msg += arguments.callee(v);
            }
            else {
            	msg += "\"" + k + "\":" + arguments.callee(v);                    	
            }
            msg += mySection;
        }
        else {
            if ( dataType == "array" ) {
                msg += v;
            }
            else {
                msg += "\"" + k + "\":";
                if ( propertyType == "string" ) {
                    msg += "\"" + v + "\"";
                }
                else {
                	msg += "" + v;
                }
            }
            msg +=  mySection;
        }
    });//jQuery.each(myData, function(k, v) {
  
    if ( isData == true ) {
        msg = msg.substring(0, msg.length-1);
    }
  
    if ( dataType == "array" ) {
        msg += "]";
    }
    else if ( dataType == "object" ) {
        msg += "}";
    }
  
    return msg;
};//var myStringify = function(data) {


posted by 뚱2
window.onload 전에 이미지나 리소스가 로딩되기 전에 일어나는 이벤트이다.
다만 ie에서는 버그가 있어서 잘 되지 않는 경우가 있다.

출처 : http://blog.iolo.pe.kr/284

onReady = (function(ie){
    var d = document;
    return ie ? function(c){
        var n = d.firstChild,
        f = function(){
            try{
                c(n.doScroll('left'))
            }catch(e){
                setTimeout(f, 10)
            }
        }; f()
    } : 
    /webkit|safari|khtml/i.test(navigator.userAgent) ? function(c){
        var f = function(){
            /loaded|complete/.test(d.readyState) ? c() : setTimeout(f, 10)
        }; f()
    } : 
    function(c){
        d.addEventListener("DOMContentLoaded", c, false);
    }
})(/*@cc_on 1@*/);

onReady(function(){

    alert("Hello DOM");

});

posted by 뚱2

위와 같은 폼이 있습니다.
조건을 선택하고 검색 버튼을 클릭하면은 해당 결과가 아래의 그리드에 나타납니다.
조건 TEXT에 입력하고 Enter키를 누르면 검색 버튼을 클릭하는것도 같은 효과를 나타내주고 싶을때 입니다.


onSubmit="return false;" 꼭 작성해 주셔야 클릭시에 폼이 자동으로 전송되는건 막아줍니다.
* onSubmit="return false;" 하는 이유 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=qna_html&wr_id=155693

jQuery(document).ready(function($) {
    $("#listForm input[name=srch_text]").keydown(function(e){
        if(e.keyCode == 13){
            e.cancelBubble = true;
            $("#btn_search").click();
            return false;
        }
    });
});
keyDown이벤트를 잡고 enter키를 확인합니다. 이벤트가 전파되지 않게 e.cancelBubble 를 true 넣어줍니다.



posted by 뚱2

if ( typeof test == 'undefined' ) 
    var test = {};

test.getIEVersion = function() {
    var myAgent = navigator.userAgent;
    var result = myAgent.match( /MSIE\s(\d{1,2}\.\d{1})/i );
    var retString = "";
    if ( result == null ) {
        retString = "none";
    }
    else {
        retString = result[1];
    }

    return retString;
};

alert(test.getIEVersion());



posted by 뚱2

if ( typeof test == 'undefined' )
    var test = {};

test.getBroswerName = function() { 
    // 아래에 검색할 브러우져 이름을 추가한다.
    var myAgent = [
         "MSIE"
        ,"FIREFOX"
        ,"CHROME"
    ];
    var currentAgent = navigator.userAgent;
    currentAgent = currentAgent.toUpperCase();
    
    for (var i = 0; i < myAgent.length; i++ ) {
        if ( currentAgent.indexOf(myAgent[i].toUpperCase()) != -1 ) {
            return myAgent[i];
        }
    }

    return "NONE";
};


//사용방법
alert(test.getBroswerName());

posted by 뚱2
기존의 C계열(C, Java)의 프로그램에서 변수의 유효범위는 {}로 정해진다.
자바스크립트도 문법은 C계통과 비슷 ( java) 하기에 당연스럽게 {}가 변수 유효범위인줄 알았다.
아래와 같이 테스트 해보니 예외가 발생하지 않는다.
결국 자바스크립트에서 변수의 유효범위는 함수기반이다.

* 확실히 하기 위해서 익명함수를 만들고 바로 try catch 구분을 걸었으며 if문 안의 {}안에 변수를
  선언했지만 결과적으로 유효하게 alert창이 출력된다.

//예외가 발생하지 않는다.
try {
    alert((function() { 
        try {
            if ( true ) {
                var myVal = "함수 안의 if 구분 안입니다.";
            }
        }
        catch(e) {alert(e.message);}
        finally  {}
        
        return myVal;
    })());
}
catch(e) {alert(e.message);}
finally  {}

posted by 뚱2

/**

* POST 방식으로 전송하는 팝업창

* url        : 팝업창 경로

* data       : object, array

* popName    : 팝업창 이름 

* popWidth   : 팝업창 가로 길이 (생략하면 화면 넓이에 맞춰진다.)

* popHeight  : 팝업창 세로 길이 (생략하면 화면 높에에 맞춰진다.)

* popOptions : 팝업창 옵션 (생략하면 기본으로 scrollbars=yes 이다.)

* comment :

*     데이터를 json 형식으로 넘겨도 된다.

*     예) gls.openPostPopup({

*             url     : 경로

*            ,data    : json data

*            ,target  : 이름

*            ,width   : 넓이

*            ,height  : 높이

*            ,options : 옵션

*         });

*     데이터가 필요없는 부분은 json property로 넣지 않아도 된다.    

*/

SEED.openPostPopup = function(obj, data, popName, popWidth, popHeight, popOptions) {

var myPop = null;

try {

var param = null;

// json object이라면

if ( obj && typeof obj == 'object' ) {

param = {

'url'     : SEED.url(obj.url)   || ''

,'data'    : obj.data                 || []

,'target'  : obj.target               || ''

,'width'   : obj.width               || screen.availWith

,'height'  : obj.height               || screen.availHeight

,'options' : obj.options             || 'scrollbars=yes'

};

}

else {

param = {

'url'     : SEED.url(obj)       || ''

,'data'    : data                     || []

,'target'  : popName                 || ''

,'width'   : popWidth                 || screen.availWith

,'height'  : popHeight               || screen.availHeight

,'options' : popOptions               || 'scrollbars=yes'

}; 

}

if ( $.type(param.data) == "object" ) {

param.data = [param.data];

}

//랜덤한 수를 출력

var curDate   = new Date();

var ranNumber = Math.floor(Math.random() * 10000) + 1;

var strId = "";

   strId += param.target;

   strId += "_";    

   strId += (new Date()).getTime();

   strId += "_" + ranNumber;

   

var $popForm = $("<form onSummit='return false;'></form>")

.attr("name"  , strId)

.attr("id"    , strId)

.attr("method", "POST");

if ( $popForm ) {

// 배열 순회

$.each(param.data, function(i, elem) {

// 객체 순회

$.each(elem, function(key, val) { 

       $("<input type='hidden'/>")

       .attr("name" , key)

       .attr("value", val)

       .appendTo($popForm);

});

});//$.each(para.data, function(i, elem) {

$popForm.appendTo(document.body);

   myPop = SEED.openWin("", param.target, null, param.width, param.height, param.options);

   var myForm = $popForm[0];

   myForm.action = param.url;

   myForm.method = "POST";

   myForm.target = param.target;

   

   // 현재 생성한 form을 삭제한다.

   myForm.submit();

   if ( $popForm.size() > 0 ) {

    $popForm.remove();

   }

}//if ( $popForm ) {

}

catch (e) {alert(e.message);}

finally   {}


return myPop;

};


posted by 뚱2
아이디어는 간단하다  Dom Object를 동적으로 생성할때나
동적으로 함수를 호출할때 리터럴 객체를 인자로 전달하는게 일반 인자를 쭉 나열하는것보다 편하다
이유는
1. 객체 쪽에 속성을 추가하면 함수 인자를 추가하는 효과가 있다.
2. 인자 리스트가 지저분하게 길어지지 않는다.
3. 인자의 순서를 신경쓸 필요가 없다.
그리고 가장 중요한 편한점중 하나는 유지보수 및 관리가 편하다는 것이다.

// 포매터
function myFormatter(cellvalue, options, rowObject) {
	var retString = "";
	var strJsonText = JSON.stringify(rowObject);
    strJsonText = strJsonText.replace(/\"/gi, "'");
    	
    // 문항관리
	if ( cellvalue.toUpperCase() == "QUESTION_MGMNT" ) {
		retString = "문항관리";
	}
    // 미리보기
	else if ( cellvalue.toUpperCase() == "PREVIEW" ) {
		retString = "미리보기";
	}
    // 진단명
	else if ( /(.+)/gi.test(cellvalue) == true ) {
		retString = "" + cellvalue + "";
	}
	else {
		retString = cellvalue;
	}
    
	return retString;
}

4-5번째 줄을 살펴보면 리터를 객체를 받아서 jsontext로 변경해서 붙여준다.
posted by 뚱2
출처 : http://jqfundamentals.com/book/index.html#chapter-1
var myFunction = function() {
    console.log('hello');
};

var myObject = {
    foo : 'bar'
};

var myArray = [ 'a', 'b', 'c' ];

var myString = 'hello';

var myNumber = 3;

typeof myFunction;   // returns 'function'
typeof myObject;     // returns 'object'
typeof myArray;      // returns 'object' -- careful!
typeof myString;     // returns 'string';
typeof myNumber;     // returns 'number'

typeof null;         // returns 'object' -- careful!


if (myArray.push && myArray.slice && myArray.join) {
    // probably an array
    // (this is called "duck typing")
}

if (Object.prototype.toString.call(myArray) === '[object Array]') {
    // Definitely an array!
    // This is widely considered as the most robust way
    // to determine if a specific value is an Array.
}



posted by 뚱2
* Javascript this에 관한 글
http://blog.mixed.kr/94


posted by 뚱2