정규표현식 사용시 슬래시 or RegExp 객체를 사용합니다.

var pattern = /a/;
var pattern = new RegExp('a');

 

 

 

 정규식 메소드 사용

//RegExp.exec();
pattern.exec('abcdef'); // ["a"]
pattern.exec('bcdefg'); // null

//RegExp.test()
pattern.test('abcdef'); // true
pattern.test('bcdefg'); // false

 

 

 

 문자열 메소드 사용

//'abcdef'.match(pattern); // ["a"]
'bcdefg'.match(pattern); // null
'abcdef'.replace(pattern, 'A');  // Abcdef 

 

 

 

Flag

//i(ignore) - 대소문자 무시 
var pattern = /a/;
var patterni = /a/i;
"Abcde".match(pattern); // null
"Abcde".match(patterni); // ["A"]

// g
var pattern = /a/;
var patterng = /a/g;
"abcde".match(pattern); //["a"]
"abcdea".match(patterng); //["a","a"]

var pattern = /a/;
var patterng = /a/ig;
"aAbcdeaA".match(patterng); //["a","A","a","A"]

 

 

 

캡쳐

var pattern = /(\w+)\s(\w+)/; var str = "My superman"; var result = str.replace(pattern, "$2, $1"); console.log(result);//superman My

 

 

치환

​​
var urlPattern = /\b(?:https?):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*/i;
var content = '티스토리 : http://tokigui.tistory.com/ 입니다.';
content += '네이버블로그: http://blog.naver.com/tokigui 입니다.';
var result = content.replace(urlPattern, function(url){
    return "" + url + "";
});
console.log(result); 

Posted by 달팽이맛나
,


스코프(scope)?

 코드에서 변수를 참조할 수 있는 해당 변수의 유효범위를 결정하는 개념


종류

 - 전역 스코프(global scope) - 코드 전체 접근 가능

 - 지역 스코프(local scope) - 함수 내의 코드에서만 접근 가능

 - 블록({}) 스코프가 존재하지 않음.







Posted by 달팽이맛나
,

ready

 - 발생시점 

  ready() 메소드에 전달되는 이벤트 핸들러 함수의 호출 시점은 DOM구조가 로딩 완료될때(1,2번 사이)


HTML 문서는 가장 먼저 

1. DOM 구조가 로딩되고

2. 이어서 이미지와 같은 요소 컨텐츠들이 로딩

3. 이후 Window 객체가 로딩되고

4. 웹브라우저에서 Window 객체의 load이벤트가 발생 



* load 이벤트  - HTML 문서가 파싱이 되고, 외부컨텐츠 로딩이 완료되면 발생





Posted by 달팽이맛나
,


preventDefault

이벤트 디폴트 동작 제어

a태그 클릭시 a태그의 기본동작인 구글로 이동을 제어하고 alert을 실행시킴


이동




Posted by 달팽이맛나
,


캡처 단계

웹 브라우저에서 이벤트가 발생하고, 문서의 최상위 객체인 Document 객체에서 이벤트가 발생한 타겟 객체의 상위 객체까지 이벤트가 전파되는 단계


타겟 단계

이벤트가 발생한 객체로 전파되는 단계


버블링 단계

타겟 객체의 상위 객체에서 다시 최상위 객체인 Document 객체까지 전파되는 단계



아래의 예제를 보면

outer 객체와 inner객체에 click 리스너가 설정되어 있다

inner를 클릭했을경우

Document 에서 타겟객체인 inner까지 캡쳐단계,타겟단계를 거쳐 이벤트가 발생하고,

다시 상위로 버블링 된다.

이때 outer에도 click 리스너가 설정되어 있기때문에 실행이 된다.

아래의 방법으로 버블링을 막을수 있다.



// 이벤트 버블링 억제 함수
function cancleBubbling(e){
    if(e.stopPropagation){//ff, crome..
        e.stopPropagation();
    }else{//ie 6,7,8
        window.event.cancleBubble = true;
    }
}

function outerFunc(){
    var result = document.getElementById('result');
    result.innerHTML = 'outer 에서 click 이벤트 발생';
}

function innerFunc(e){
    var result = document.getElementById('result');
    result.innerHTML = 'inner 에서 click 이벤트 발생';
   cancleBubbling(e);
}

function init(){
    var outer = document.getElementById('outer');
    var inner = document.getElementById('inner');

    addListener(outer, 'click', outerFunc);
    addListener(inner, 'click', innerFunc);
}

function addListener(el, ev, handler){
    if(el.addEventListener){
        el.addEventListener(ev, handler, false);
    }else{
        el.attachEvent('on' + ev, handler);
    }
}

addListener(window, 'load', init);


		
외부영역을
내부 영역을 클릭해 보세요
클릭해 보세요!!
...


Posted by 달팽이맛나
,

load 이벤트

HTML 문서가 파싱이 되고, 외부컨텐츠 로딩이 완료되면 발생

 

htmlElement.이벤트핸들러프로퍼티명 =  = function(){
    //수행문장
};

window.onload = function(){
    //수행문장
};


Posted by 달팽이맛나
,

 

JSON

 

JSON은 자바스크립트에서 객체를 텍스트로 표현하는 방식.

 

JSON은 시스템 간의 데이터 교환의 수단으로 사용되고 있는 XML보다

용량이 작고, 파싱에 걸리는 시간이 절약되는 이유로 시스템 간의 데이터 교환에 많이 사용되고 있으며,

웹 환경에 최적화되어 있는 자바스크립트에서

바로 객체화해 사용할 수 있기 때문에 생산성과 편의성 또한 높음.

 

JSON은 숫자, 문자열, 불리언, 배열, 긱체를 표현할수 있음.

 

// JSON
var orderJSON = '{"name":"정도전","address":"서울시 종로구","jobs":[{"name":"조립", "pay":100},{"name":"분해", "pay":200}],"man":true}';
var order = JSON.parse(orderJSON);

console.log('order.name: ' + order.name);
console.log('order.address: ' + order.address);

for(var i=0; i < order.jobs.length; i++){
    for(prop in order.jobs[i]){
        console.log(prop + ': ' + order.jobs[i][prop]);
    }
}
console.log('order.man: ' + order.man);


/*
order.name: 정도전
order.address: 서울시 종로구
name: 조립
pay: 100
name: 분해
pay: 200
order.man: true
 * */
Posted by 달팽이맛나
,

 

Date

 

Date 객체는 리터럴 표현이 존재하지 않으며, new 연산자와 생성자 호출을 통해

객체를 생성해야함.

 

Date 객체는 1970년 1월 1일 0시 0분 0초를 기준으로 시간을 관리하며,(epoch time)

Date 객체의 월 지정값을 0~11

 

var d = new Date();
document.writeln(d);//Fri Jan 17 2014 13:17:32 GMT+0900 0 2014 
document.writeln(d.getFullYear());//2014 년
document.writeln(d.getMonth());//1 월 0~11임(0 :1월, 11:12월)
document.writeln(d.getDate());//17 일
document.writeln(d.getDay());//요일(0:일요일 ~ 6:토요일)

var d = new Date('2013/12/10');
var d = new Date(2012, 11, 10, 22, 10, 33, 500);
Posted by 달팽이맛나
,

 

 

프로토타입 상속을 한 사용자 정의 객체를 사용할때는

typeof, instanceof, constructor 프로퍼티, toString() 메소드등의

도움을 얻어 판달할 필요가 있음.

var Parent = function(){};
Parent.prototype.constructorname = 'Parent';

var Child = function(){};
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.constructorname = 'Child';

var child = new Child();
document.writeln('typeof Parent : ' + typeof Parent + '
'); document.writeln('typeof Child : ' + typeof Child + '
'); document.writeln('typeof child : ' + typeof child + '
'); /* return: typeof Parent : function typeof Child : function typeof child : object * */ document.writeln('child instancdof Object : ' + ( child instanceof Object) + '
'); document.writeln('child instancdof Parent : ' + ( child instanceof Parent) + '
'); document.writeln('child instancdof Child : ' + ( child instanceof Child) + '
'); /* return: child instancdof Object : true child instancdof Parent : true child instancdof Child : true * */ document.writeln('child.constructor === Object: ' + ( child.constructor === Child) + '
'); document.writeln('child.constructor === Parent: ' + ( child.constructor === Parent) + '
'); document.writeln('child.constructor === Child: ' + ( child.constructor === Child) + '
'); /* return: child.constructor === Object: true child.constructor === Parent: false child.constructor === Child: true * */ function checkType(obj){ // null일 경우 문자열 'null' 반환 if(obj === null){ return 'null'; } //typeof가 'object'가 아닐경우 type반환 var type = typeof obj; if(type != 'object'){ return type; } //obj.toString()의 결과를 저장 var str = Object.prototype.toString.call(obj); // 생성자 이름 추출 var constructor = str.substring(8, str.length - 1); if(constructor != 'Object'){ return constructor; } if(obj.constructor == 'Object'){ return constructor; } // 사용자 정의 객체의 생성자 함수의 프로토타입 객체에 정의해 놓은 constructorname // 프로퍼티가 있으면 constructorname을 반환 if('constructorname' in obj.constructor.prototype) return obj.constructor.prototype.constructorname; return '객체의 타입을 알수 없습니다.'; } document.writeln('checkType(child) : ' + checkType(child) + '
'); /* return: checkType(child) : Child * */
Posted by 달팽이맛나
,
// Car 생성자 함수의 프로토타입 객체는 new 연산자와 Object 생성자 함수 호출을 통해 생성된 객체이며
// 프로토타입 객체에 constructor 프로퍼티는 자동으로 Car 생성자 함수를 참조한다.
var Car = function(){};

Car.prototype = {
   startEngine : function(){
       document.writeln('시동을 겁니다.
'); }, accelerate : function(){ document.writeln('속도를 올립니다.
'); }, decelerate : function(){ document.writeln('속도를 줄입니다.
'); }, stopEngine : function(){ document.writeln('시동을 끕니다.
'); } }; // Bus 생성자 함수의 프로토타입 객체는 new 연산자와 Object 생성자 함수 호출을 통해 생성된 객체이며, // 프로토타입 객체에 constructor 프로퍼티는 자동으로 Bus 생성자 함수를 참조합니다. var Bus = function(){}; // Bus() 생성자 함수의 prototype 프로퍼티가 new 연산자와 Car() 생성자 함수 호출을 통해 생성된 객체를 참조하면 // Car() 생성자 함수의 프로토타입 멤버를 상속하게 됩니다. Bus.prototype = new Car(); // 프로토타입 객체가 Car() 생성자 함수를 통해 만들어졌기 때문에 constructor 프로퍼티는 // Car() 생성자 함수를 참조하게 됩니다. 따라서 constructor 프로퍼티를 Bus() 생성자 함수로 변경합니다. Bus.prototype.constructor = Bus; Bus.prototype.startNavigation = function(){ document.writeln('네비게이션 안내를 시작합니다.
'); }; Bus.prototype.stopNavigation = function(){ document.writeln('네비게이션 안내를 종료합니다.
'); }; var bus = new Bus(); bus.startEngine(); bus.startNavigation(); bus.accelerate(); bus.decelerate(); bus.stopNavigation(); bus.startEngine(); /* result : 시동을 겁니다. 네비게이션 안내를 시작합니다. 속도를 올립니다. 속도를 줄입니다. 네비게이션 안내를 종료합니다. 시동을 겁니다. */
Posted by 달팽이맛나
,