1.변수
2.표현식
3.객체 & 배열
4.함수(first class object)
5.상속
6.키워드로 본 스크립트 정리
<script language="javascript">
/*
자바스크립트 에서 변수를 선언할때는 반드시 var 를
사용해야 한다. var 가 사용되지 않은 변수는
전역변수 가 되어진다. 그러므로 전역변수 이던지
지역변수 이던지 구분하지 말고 모든 변수에는 var 를
반드시 기술해야 한다.
*/
var scope1 = "outer";
(function fnc1(){
var scope1 = "inner";
alert(scope1);
})();
scope2 = "outer2";
(function fnc2(){
scope2 = "inner2";
alert(scope2);
innerScope = "innerScope";
})();
alert(scope2);
alert(innerScope);
/////////////////////////////////////////////////////////////////
/*
자바스크립트에서의 유효범위는 크게 2가지로 나뉜다고 볼수 있다.
하나는 함수로서의 유효범위(클로저에서 살펴볼것임)와
변수가 가지는 블럭단위의 유효범위가 있다
*/
(function fnc3(pVal){
var i = 0;
if(typeof pVal === "object"){
var j = 0;
for(var k = 0; k <10; k++){
document.write(k + "<br>");
j = j + 1;
}
alert(k); //????
}
alert(j); //????
})({}); // 매개변수 {} 가 들어갔을 경우와 안들어 갔을 경우이 차이점은??
//////////////////////////////////////////////////////////////////
/*
자바스크립트에서 지역변수 는 함수 전체에 걸쳐서 정의된다.
즉 같은 이름의 변수는 함수 전체에서 지역변수에 의해
감춰진다. 단 이 지역변수가 함수 전체에서 정의되어 있기는 하지만
var 문이 실행되고 나서야 초기화 된다.
*/
var scope4 = "outer4";
(function fnc4(){
alert(scope4); // ????
var scope4 = "inner4";
alert(scope4); // ????
})();
//////////////////////////////////////////////////////////////////
</script>
자바스크립트에서 표현식 == 은 예기치 못한 문제를 일으킬 우려가
있으므로 피치 못할 사정이 아니라면 표현식 === 를 사용해라
<script language="javascript">
(function(){
if(1 == "1")
alert('true : 1 == "1" ');
if(1 == true)
alert('true : 1 == true ');
if("1" == true)
alert('true : "1" == true ');
if("true" != true)
alert('true : "true" != true ');
if(false != "false")
alert('true : false != "false" ');
/////////////////////////////////////////
if(1 !== "1")
alert('true : 1 !== "1" ');
if(1 !== true)
alert('true : 1 !== true ');
if("1" !== true)
alert('true : "1" !== true ');
if("true" !== true)
alert('true : "true" !== true ');
/////////////////////////////////////////
if("" != "0")
alert('true : "" != "0" ');
if("" == 0)
alert('true : "" == 0 ');
if(0 == '0')
alert('true : 0 == "0" ');
})()
</script>
규칙
1.불리언 값이 숫자 문맥에 사용되면 true 는 숫자 1 로 false 는 숫자 0으로 변환
2.숫자가 불리언 값을 기대 하는 곳에서 사용된다면 숫자가 0 혹은 NaN 인경우 false 로 그 이외에는 true로 변환
3.문지열이 불리언 값을 기대 하는 곳에서 사용된다면 빈 문자열은 false 로 그 이외에는 true로 변환
4.null과 undefined 값은 false 로 변환되고 null 이 아닌 객체나 배열 함수는 true로 변환
자바스크립트에서는 위에 규칙에 의거해서 명시적이 아니라 자동으로 형변환이 이루어 진다.
!! 표현식을 이용해서 명시적으로 표현하자
<script language="javascript">
(function(pVal){
if(pVal){
//...
}
if(!pVal){
//...
}
if(!!pVal){
//...
}
})({})
</script>
<script language="javascript">
(function(pVal){
/*
instanceof 는 좌변의 피연산자로 객체를 우변의 피연산자로 클래스를 받는다.
*/
var dt = new Date();
if(dt instanceof Object)
alert("true : dt instanceof Object");
if(dt instanceof Date)
alert("true : dt instanceof Date");
if( !(dt instanceof Number) )
alert("true : !(dt instanceof Number) ");
//////////////////////////////////////////////////
/*
typeof 는 피연산자의 데이터 타입을 문자열로 돌려준다.
*/
if(typeof {} === "object")
alert( 'true : typeof {} === "object" ');
if(typeof "hello" === "string")
alert( 'true : typeof "hello" === "string" ');
if(typeof 1 === "number" )
alert( 'true : typeof 1 === "number" ');
})({})
</script>
<script language="javascript">
var SampleObj = function(pName, pAge){
this.name = pName;
this.age = pAge;
}
SampleObj.prototype.specise = 'humen';
function outFnc1(pVal){
if(!!pVal){
for(mv in pVal){
if(pVal.hasOwnProperty(mv)){
document.write('SampleObj.' + mv + " = " + pVal[mv]);
document.write("<br>");
}
}
}else{
alert("error");
}
}
function outFnc2(pVal){
if(!!pVal){
for(mv in pVal){
document.write('SampleObj.' + mv + " = " + pVal[mv]);
document.write("<br>");
}
}else{
alert("error");
}
}
outFnc1(new SampleObj('simson', 29, 'Man'));
document.write("==========================" + "<br>");
outFnc2(new SampleObj('simson', 29, 'Man'));
</script>
자바스크립트에서 arguments 키워드는
배열처럼 동작 하고 length 속성도 있지만 배열이 제공해 주는 메소드는 없다.
<script language="javascript">
var sum = function(){
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};
alert(sum(4, 8, 15, 16, 23, 42)); // 108
var a = {};
var i = 0;
while( i < 10 ){
a[i] = i * i;
i++
}
a.length = i;
var total = 0;
for(var j =0; j < a.length; j++){
total += a[j];
}
alert(total);
</script>
자바스크립트에서 단순데이터 타입인 숫자, 문자열, 불리언, null
undefined 를 제외한 다른 모든것들은 객체다.
(함수도 객체다)
<script language="javascript">
var sampleObj = {};
var sampleObj2 = {
"name": "coolGuy",
age: 19
}
alert(sampleObj2.age);
alert(sampleObj2["age"]);
alert(sampleObj2["name"]);
alert(sampleObj2[name]);
var sampleObj3 = function(){
};
sampleObj3.prototype.name = 'coolMan2';
sampleObj3.prototype.age = 19;
var obj = new sampleObj3();
alert(obj.name);
alert(obj[name]);
alert(obj["age"]);
</script>
배열의 첨자로 문자열을 사용할수 있다는 점과
다차원 배열이 없다는 것만 기억 하면 사용법은 다른 언어와 다름이 없다.
유사 배열 과 arguments 예제 에서 살펴보았듯이
일반 객체로도 얼마든지 배열을 만들어 낼수있다.(속도도 사실상 차이가 없다.)
typeof 연산자로 배열을 확인해 보면 리턴 값이 "array" 가 아니라 "object" 이다.
배열을 써야 할때( new Array Or [] ) 와 객체를 써야할때의 기준은 다음과 같다.
속성이름이 작은 크기의 연속된 정수 이면 배열을 사용하고 그렇지 않다면 객체를 사용한다.
<script language="javascript">
var arr = new Array();
//arr[0][0] = 'something'; <-- 다차원 배열이라면 이 문법이 가능해야함
var arr2 = {
0 : 'somethibg',
1 : ['a','b','c']
};
alert(arr2[1][0]);
arr = ['a','b','c',['d','e','f']];
alert(arr[3][1]);
</script>
h3.prototype & constructor
모든 함수에는 미리 정의된 prototype 객체를 가르키는 prototype 속성(프로퍼티)가 있다.
함수를 new 연산자와 함께 호출할 경우
호출된 함수의 prototype 속성을 가르키는 객체가 생성되고
이객체는 this에 바인딩 된다.
<script language="javascript">
var Parent2 = function(name, age){
this.name = name;
this.age = age;
}
Parent2.prototype.getInfo = function(){
return "name : " + this.name + " age : " + this.age
}
var test4 = new Parent2('eva', '20');
var test5 = new Parent2('hito', '20');
var test6 = new Parent2('heo', '20');
alert(test4.getInfo());
alert(test5.getInfo());
alert(test6.getInfo());
////////////////////////////////////////////////////////////
var Obj = function(name){
this.name = name;
}
Obj.prototype.Nature = 'Pure';
init_obj1 = new Obj('good');
init_obj2 = new Obj('bad');
alert(init_obj1.name); //1
alert(init_obj1.Nature); //2
alert(init_obj2.name); //4
alert(init_obj2.Nature); //5
</script>
모든 함수에는 prototype 프로퍼티가 있다.
이것은 함수가 정의될때 부터 자동적으로 생성되고 초기화 된다.
prototype 프로퍼티의 초기값은 프로퍼티가 하나있는 객체로 지정된다.
이 한개의 프로퍼티는 constructor 이다.
constructor 프로퍼티는 prototype 프로퍼티가 연관되어 있는 생성자 함수를 가르킨다.
//예상된 구현 코드
var prototype = {constructor : this};
<script language="javascript">
var Obj = function(name){
this.name = name;
}
alert(Obj.prototype.constructor);
//Obj.prototype.Nature = 'Pure';
</script>
new 로 생성된 모든 객체는 constructor 프로퍼티를 가지고 있다.
new 로 생성된 객체가 가진 constructor 프로퍼티는 자신의 생성자 함수를 가르킨다.
new 로 생성된 객체가 가진 프로퍼티에 접근할때 값이 없다면 constructor 의 prototype 프로퍼티 하위에 존재 하는 값을 찾는다.
없다면 prototype 의 constructor의(한단계 상위의 생성자 함수) prototype 프로퍼티 하위에 존재 하는 값을 찾는다.
이런 과정이 최상위 Super 생성자이 Object 에 도달할때 까지 반복 되며, 그래도 값이 없다면 undefined 값을 돌려준다.
과거 구 브라우저와 FF 에서는 __proto__ 라는 속성을 제공하는데 이는
constructor.prototype 을 축약한 형태이다.
<script language="javascript">
var Obj = function(name){
this.name = name;
this.Nature = 'dirty'
}
Obj.prototype.Nature = 'Pure';
init_obj1 = new Obj('good');
//alert(init_obj1.prototype); <---- ????
alert(Obj.prototype.constructor);
alert(init_obj1.constructor);
alert(init_obj1.Nature);
alert(init_obj1.constructor.prototype.Nature);
alert(init_obj1.__proto__.Nature);
</script>
h3.호출방법에 따른 패턴 구분(this의 사용법)
자바스크립트에서는 this 의 역할은 함수의 호출 방법에 따라 초기화 하는 방법이 달라진다.
함수를 객체의 속성으로 지정하는 경우를 메소드 라고 한다.
이렇게 메소드 로서 사용될때
this는 객체를 가르킨다. 혹은
this는 객체에 바인딩 되었다. 라고 표현 한다.
호출시점에 객체와 this 간의 바인딩 이 이루어 지며
직관적인 설계가 가능한점이 장점이다.
단점으로는 모든 속성이 public 이 되기 때문에 보안상 문제가
될 소지가 있다
<script language="javascript">
var sampleObject = {
name: 'user',
value: 0,
getName: function(){
alert(this.name);
},
add: function(a, b){
this.value = a + b;
}
}
sampleObject.getName(); //호출 시점
alert(sampleObject.value); //호출 시점
sampleObject.add(2, 3); //호출 시점
alert(sampleObject.value); //호출 시점
</script>
함수가 객체의 속성이 아닌경우.
단순 함수 호출이 된다.
이경우 this 는 전역객체(보통 window 객체)에 바인딩 된다.
문제가 있다면 함수 안에서 함수를 호출 하는 구문을 작성할경우
(보통 프레임워크를 설계 하다 보면 자주 발생한다.)
내부 함수가 자신의 객체에 접근 하기 위해 사용하는
this 에 자신의 this (보통 부모 함수)가 아니라 전역객체(widow 객체)
를 바인딩 하게 된다.
<script language="javascript">
function add(a, b){
return a * b;
}
var sampleObject = {
value: 0,
add: function(a, b){
this.value = a + b;
return this.value;
},
outerFnc: function(){
var that = this;
var innerFnc1 = function(){
var sum = this.add(10, 10);
alert("innerFnc1 : " + sum);
}
var innerFnc2 = function(){
var sum = that.add(10, 10);
alert("innerFnc2 : " + sum);
}
innerFnc1(); //함수 호출
innerFnc2(); //함수 호출
}
}
sampleObject.outerFnc();
</script>
함수를 new 연산자와 함께 호출할 경우
호출된 함수의 prototype 속성을 가르키는 객체가 생성되고
이객체는 this에 바인딩 된다.
<script language="javascript">
var sampleObj = function(obj){
this.name = obj.name || 'noName';
this.age = obj.age || 0;
}
sampleObj.prototype.getInfo = function(){
alert('name : ' + this.name + "\n"
+'age : ' + this.age
)
}
var initObj1 = {
name : 'haveName',
age : 19
}
var tdd1 = new sampleObj(initObj1); //생성자 호출
tdd1.getInfo();
var initObj2 = {
age : 12
}
var tdd2 = new sampleObj(initObj2); //생성자 호출
tdd2.getInfo();
</script>
apply(call)을 이요한 호출은 대상이 되는
함수의 this를 첫번째 인자로 넘겨 주는 객체의 this로
변경한다.
(책에 따라서는 컨텍스트 라는 용어를 사용하기도 한다.
ex: applly 는 함수의 대상함수의 컨텍스트를 첫번째 객체인자의
컨텍스트로 변경한다.등등..
)
<script language="javascript">
var sampelAdd = function(a, b){
return a + b;
}
var sampleObj = function(obj){
this.name = obj.name || 'noName';
this.age = obj.age || 0;
}
sampleObj.prototype.getInfo = function(){
alert('name : ' + this.name + "\n"
+'age : ' + this.age
)
}
sampleObj.prototype.setInfo = function(pName, pAge){
this.name = pName;
this.age = pAge;
alert('name : ' + this.name + "\n"
+'age : ' + this.age
)
}
var array = [10,12];
var info = {
name : 'coolman',
age : 12
};
var newInfoArr = ['superCoolman',20];
/*
appay는 아래와 같이 사용됨
[functionObj].apply(thisObj,arguArray)
thisObj 가 제공되지 않을경우 전역객체가 thisObj로 사용되고 인수는 전달 되지 않음
*/
alert(sampelAdd.apply('',array)); // sampelAdd.apply(null,array)
sampleObj.prototype.getInfo.apply(info); //sampleObj.prototype.getInfo.apply('',info); 이 주석 구문은 에러다 왜일까?
sampleObj.prototype.setInfo.apply(info,newInfoArr);
</script>
h3.확장(기본타입에 기능추가)
javascript 의 native Function 에 기능을 추가해 보자
<script language="javascript">
String.prototype.trim = function(){
var re = /^\s+|\s+$/g;
return this.replace(re, '');
}
alert("hello" + " helloBabyyo ".trim() + " keroro ".trim());
String.prototype.entityify = function(){
var that = this;
var character = {
'<' : '<',
'>' : '>',
'&' : '&',
'"' : '"'
};
var re = /[<>&"]/g;
var inFnc = function(){
return that.replace(
re,
function(c){
return character[c];
}
);
};
return inFnc();
};
alert("<".entityify());
alert(">".entityify());
alert("&".entityify());
alert("\"<&>\"".entityify());
</script>
h3.클로저
함수안에 함수를 넣고 내부함수에서 외부 함수의 변수를 리턴 시키는 문장 구조를 만들면 클로저가 된다.
사용 용도는 private 구조를 만들거나 메모이제이션과 같은 효과를 얻기 위해 사용되어진다.
장정도 크지만 남용하게 되면 메모리 문제로 사이트가 느려지거나 브라우저가 죽는 문제를 일으키다.
<script language="javascript">
var sampleObj = function(pVal){
return {
getVal: function(){
return pVal
}
}
};
var myObj = sampleObj('1234');
alert(myObj.getVal());
///////////////////////////////////////
var makeUnique = (function(){
var unique = 0;
return {
getUniqueNum: function(){
return unique++;
}
}
})();
alert(makeUnique.getUniqueNum());
alert(makeUnique.getUniqueNum());
alert(makeUnique.getUniqueNum());
alert(makeUnique.getUniqueNum());
///////////////////////////////////////
String.prototype.entityify = (function(){
var character = {
'<': '<',
'>': '>',
'&': '&',
'"': '"'
};
var re = /[<>&"]/g;
var inFnc = function(){
return this.replace(re, function(c){
return character[c];
});
};
return inFnc;
})();
alert("<".entityify());
alert(">".entityify());
alert("&".entityify());
alert("\"<&>\"".entityify());
////////////////////////////////////////
var fivoFnc = function(n){
return n < 2 ? n : fivoFnc(n - 1) + fivoFnc(n - 2)
}
console.time("noUseCloser");
document.write(fivoFnc(25));
console.timeEnd("noUseCloser");
var fivoFnc2 = (function(){
var memo = [0, 1];
var fib = function(n){
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
}
return fib;
})();
console.time("useCloser");
document.write(fivoFnc2(40));
console.timeEnd("useCloser");
</script>
자바스크립트에서 상속은 다양한 형태로 구현 될수 있다.
<script language="javascript">
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
function Author(name, book){
Person.apply(this, [name]);
this.book = book;
}
Author.prototype = new Person();
Author.prototype.constructor = Author;
Author.prototype.getBook = function (){
return this.book;
}
var arr = [];
arr[0] = new Author('me', 'wins gone');
arr[1] = new Author('you', 'shes gone');
arr[2] =new Author('her', 'his gone');
alert(arr[1].getName());
alert(arr[2].getBook());
</script>
<script language="javascript">
/*
var objArr =
{
subClass : function(){};
superClass : function(){};
}
*/
function extend (objArr){
if(!!objArr && !!(objArr.subClass)
&& !!(objArr.superClass)){
var F = function(){};
F.prototype = objArr.superClass.prototype;
objArr.subClass.prototype = new F();
objArr.subClass.prototype.constructor = objArr.subClass;
objArr.subClass.superClass = objArr.superClass.prototype;
}
}
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
///////////////////////////////////////////
function Author(name, book){
Author.superClass.constructor.apply(this, [name]);
this.book = book;
};
var sample = {
subClass : Author,
superClass : Person
}
extend(sample);
Author.prototype.getBook = function(){
return this.book;
};
Author.prototype.getName = function(){
var name = Author.superClass.getName.apply(this)
return name + ', Author of ' + this.getBook();
};
var arr = [];
arr[0] = new Author('me', 'wins gone');
arr[1] = new Author('you', 'shes gone');
arr[2] =new Author('her', 'his gone');
alert(arr[1].getName());
alert(arr[2].getBook());
</script>
<script language="javascript">
/*
var obj = {
useObject : someObj,
targetFnc : targetFunction(){}
}
*/
function bindMethod(obj){
if(!!obj && !!(obj.useObject)
&& !!(obj.targetFnc)){
return function(){
return obj.targetFnc.apply(obj.useObject, arguments);
};
}
};
function cloneMethod(pFrom, pTo){
var vFrom = pFrom.prototype;
var vTo = pTo.prototype;
for(mm in vFrom){
if(typeof vFrom[mm] !== 'function') continue;
if(!vTo[mm])vTo[mm] = vFrom[mm];
}
}
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
var Author = {
name : 'coolGuy',
book : 'wins gone buy buy go',
getBook : function(){
return this.book;
}
}
var sample = {
useObject : Author,
targetFnc : Person.prototype.getName
}
Author.getName = bindMethod(sample);
alert(Author.getName());
var NeedFnc = function(pName, pBook){
this.name = pName;
this.book = pBook
}
cloneMethod(Person,NeedFnc)
var sampel2 = new NeedFnc('garibong','regend Books');
alert(sampel2.getName());
</script>
h3.Cascading
//sampleFramework.js
(function(){
function _$(els){
this.elements = [];
for (var i = 0, len = els.length; i < len; ++i) {
var element = els[i];
if (typeof element == 'string') {
element = document.getElementById(element);
}
this.elements.push(element);
}
}
_$.prototype = {
each: function(fn){
for (var i = 0, len = this.elements.length; i < len; ++i) {
fn.call(this, this.elements[i]);
}
return this;
},
setStyle: function(prop, val){
this.each(function(el){
el.style[prop] = val;
});
return this;
},
show: function(){
var that = this;
this.each(function(el){
that.setStyle('display', 'block');
});
return this;
},
addEvent: function(type, fn){
var add = function(el){
if (window.addEventListener) {
el.addEventListener(type, fn, false);
}
else
if (window.attachEvent) {
el["e"+type+fn] = fn;
el[type+fn] = function() { el["e"+type+fn]( window.event ); };
el.attachEvent('on' + type, el[type+fn]);
//el.attachEvent('on' + type, fn);
}
};
this.each(function(el){
add(el);
});
return this;
}
};
window.$ = function(){
return new _$(arguments);
};
})();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Document </TITLE>
<script language="javascript" src='./sampleFramework.js'></script>
<script language="javascript">
$(window).addEvent('load', function(){
$('test-1', 'test-2')
.show()
.setStyle('borderColor', 'blue');
$('test-1', 'test-2').addEvent('click', function(e){
$(this).setStyle('borderColor', 'green');
});
});
</script>
</HEAD>
<BODY>
<table id='test-1' style='display:none;' width="200" height="200" border="20">
<tr><td><input type='text' value='test-1' /></td></tr>
</table>
<table id='test-2' style='display:none;' width="200" height="200" border="20">
<tr><td><input type='text' value='test-2' /></td></tr>
</table>
</BODY>
</HTML>
다양한 프레임워크를 사용할 경우 $의 표현법만을 이용한 접근은 사용상 제약이 많다.
사용자로 하여금 다른 첨자를 선택할수 있게 메소드를 추가
//sampleFramework.js
(function(){
function _$(els){
}
_$.prototype = {
each: function(fn){
},
setStyle: function(prop, val){
},
show: function(){
},
addEvent: function(type, fn){
}
};
window.$ = function(){
return new _$(arguments);
};
//추가된 메소드
window.initializer = function(scope, interface) {
scope[interface] = function() {
return new _$(arguments);
};
})();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Document </TITLE>
<script language="javascript" src='./sampleFramework.js'></script>
<script language="javascript">
initializer(window, 'get');
get(window).addEvent('load', function(){
get('test-1', 'test-2')
.show()
.setStyle('borderColor', 'blue');
get('test-1', 'test-2').addEvent('click', function(e){
get(this).setStyle('borderColor', 'green');
});
});
</script>
</HEAD>
<BODY>
<table id='test-1' style='display:none;' width="200" height="200" border="20">
<tr><td><input type='text' value='test-1' /></td></tr>
</table>
<table id='test-2' style='display:none;' width="200" height="200" border="20">
<tr><td><input type='text' value='test-2' /></td></tr>
</table>
</BODY>
</HTML>
h3.Factory
(
//sampleFramework.js
function(){
window.sampleXHRFactory = function(){
}
sampleXHRFactory.prototype = {
request: function(method, url, callback, postVars){
var xhr = this.createXhrObject();
xhr.onreadystatechange = function(){
if (xhr.readyState !== 4)
return;
(xhr.status === 200) ? callback.success(xhr.responseText, xhr.responseXML) : callback.failure(xhr.status);
};
xhr.open(method, url, true);
if (method !== 'POST')
postVars = null;
xhr.send(postVars);
},
createXhrObject: function(){
var methods = [
function(){return new XMLHttpRequest();},
function(){return new ActiveXObject('Microsoft.XMLHTTP');},
function(){return new ActiveXObject('Msxml2.XMLHTTP');},
function(){return new ActiveXObject('MSXML2.XMLHTTP.3.0');},
function(){return new ActiveXObject('MSXML2.XMLHTTP.4.0');},
function(){return new ActiveXObject('MSXML2.XMLHTTP.5.0');}
];
for (var i = 0, len = methods.length; i < len; i++) {
try {
methods[i]();
}
catch (e) {
continue;
}
this.createXhrObject = methods[i];
return methods[i]();
}
throw new Error('sampleXHRFactory: Can not create an XHR object.');
}
};
})();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Document </TITLE>
<script language="javascript" src='./sampleFramework.js'></script>
<script language="javascript" src='./sampleXHRFactory.js'></script>
<script language="javascript">
$(window).addEvent('load', function(){
$('test-1', 'test-2')
.show()
.setStyle('borderColor', 'blue')
.addEvent('click', function(e){
$(this).setStyle('borderColor', 'green');
});
var myHandler = new sampleXHRFactory();
var callback = {
success: function(responseText) { alert('Success: ' + responseText); },
failure: function(statusCode) { alert('Failure: ' + statusCode);
}
};
$('btn1').addEvent('click', function(e){
myHandler.request('GET', "./sample.jsp", callback);
});
$('btn2').addEvent('click', function(e){
myHandler.request('GET', "http://dev.jquery.com/~john/xdomain/test.php", callback);
});
});
</script>
</HEAD>
<BODY>
<table id='test-1' style='display:none;' width="200" height="200" border="20">
<tr><td><input id='btn1' type='button' value='sampleXHRFactory1' /></td></tr>
</table>
<table id='test-2' style='display:none;' width="200" height="200" border="20">
<tr><td><input id='btn2' type='button' value='sampleXHRFactory2' /></td></tr>
</table>
</BODY>
</HTML>
Factory 부분은 굳이 모듈화(또다른 JS 파일로 분리될)할 필요가 없다.jQuery 의 플러그인 처럼 확장 가능한
형태로 upgrade 하자(숙제)