티스토리 뷰
1. By Direct Assignment
var myApp = {}
myApp.id = 0;
myApp.next = function() {
return myApp.id++;
}
myApp.reset = function() {
myApp.id = 0;
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
); //0, 1, undefined, 0
var myApp = {}
myApp.id = 0;
myApp.next = function() {
return this.id++;
}
myApp.reset = function() {
this.id = 0;
}
myApp.next(); //0
myApp.next(); //1
var getNextId = myApp.next;
getNextId(); //NaN whoops!
2. Using Object Literal Notation
var myApp = {
id: 0,
next: function() {
return this.id++;
},
reset: function() {
this.id = 0;
}
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
3. Module Pattern
var myApp = {
id: 0,
next: function() {
return this.id++;
},
reset: function() {
this.id = 0;
}
}
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
4. Supply a Namespace Argument
var myApp = {};
(function(context) {
var id = 0;
context.next = function() {
return id++;
};
context.reset = function() {
id = 0;
}
})(myApp);
window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
var myApp = {};
(function(context) {
var id = 0;
context.next = function() {
return id++;
};
context.reset = function() {
id = 0;
}
})(this);
window.console && console.log(
next(),
next(),
reset(),
next()
) //0, 1, undefined, 0
var subsys1 = {}, subsys2 = {};
var nextIdMod = function(startId) {
var id = startId || 0;
this.next = function() {
return id++;
};
this.reset = function() {
id = 0;
}
};
nextIdMod.call(subsys1);
nextIdMod.call(subsys2,1000);
window.console && console.log(
subsys1.next(),
subsys1.next(),
subsys2.next(),
subsys1.reset(),
subsys2.next(),
subsys1.next()
) //0, 1, 1000, undefined, 1001, 0
nextIdMod();
window.console && console.log(
next(),
next(),
reset(),
next()
) //0, 1, undefined, 0
//library code
var protoQueryMooJo = function() {
//everything
}
//user code
var thirdParty = {};
protoQueryMooJo.apply(thirdParty);
'웹개발 > Javascript' 카테고리의 다른 글
| 자바스크립트 시간 계산 샘플 (1) | 2010.12.20 |
|---|---|
| Understanding JavaScript Prototypes. (0) | 2010.12.14 |
| Javascript RegEx Api (0) | 2010.12.14 |
| Javascript 키워드 몇가지 (0) | 2010.12.14 |
| 자바 스크립트 String 메서드 Split , Join 사용 예 (0) | 2010.12.14 |
댓글