Closure در JavaScript
نویسنده: شاهین کیاست
تاریخ: ۱۳۹۱/۰۴/۰۴ ۷:۱۸
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
// The getDate() function returns a nested function which refers the 'date' variable defined
// by outer function getDate()
function getDate() {
var date = new Date(); // This variable stays around even after function returns
// nested function
return function () {
return date.getMilliseconds();
}
}
// Once getDate() is executed the variable date should be out of scope and it is, but since // the inner function // referenes date, this value is available to the inner function. var dt = getDate(); alert(dt()); alert(dt());
function myNonClosure() {
var date = new Date();
return date.getMilliseconds();
}
var MyDate = function () {
var date = new Date();
var getMilliSeconds = function () {
return date.getMilliseconds();
}
}
var dt = new MyDate();
alert(dt.getMilliSeconds()); // This will throw error as getMilliSeconds is not accessible.
// This is closure
var MyDate = function () {
var date = new Date(); // variable stays around even after function returns
var getMilliSeconds = function () {
return date.getMilliseconds();
};
return {
getMs : getMilliSeconds
}
}
var dt = new MyDate(); alert(dt.getMs()); // This should work.
(function($) {
// $() is available here
})(jQuery);
// file1.js
function saveState(obj) {
// write code here to saveState of some object
alert('file1 saveState');
}
// file2.js (remote team or some third party scripts)
function saveState(obj, obj2) {
// further code...
alert('file2 saveState");
}
<script src="file1.js" type="text/javascript"></script> <script src="file2.js" type="text/javascript"></script>
function App() {
var save = function (o) {
// write code to save state here..
// you have acces to 'o' here...
alert(o);
};
return {
saveState: save
};
}
var app = new App();
app.saveState({ name: "rajesh"});