티스토리 뷰

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);

댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함