Skip to content

Instantly share code, notes, and snippets.

@TracerLee
Created April 1, 2016 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TracerLee/ca6895631c96ca99103c084aa5722d63 to your computer and use it in GitHub Desktop.
Save TracerLee/ca6895631c96ca99103c084aa5722d63 to your computer and use it in GitHub Desktop.
IIFE
// 创建一个立即执行的匿名函数
// 该函数返回一个对象,包含你要暴露的属性
var counter = (function(){
var i = 0;
return {
get: function(){
return i;
},
set: function( val ){
i = val;
},
increment: function() {
return ++i;
}
};
}());
// counter其实是一个对象
counter.get(); // 0
counter.set( 3 );
counter.increment(); // 4
counter.increment(); // 5
counter.i; // undefined i并不是counter的属性
i; // ReferenceError: i is not defined (函数内部的是局部变量)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment