Created
April 1, 2016 19:43
-
-
Save TracerLee/ca6895631c96ca99103c084aa5722d63 to your computer and use it in GitHub Desktop.
IIFE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 创建一个立即执行的匿名函数 | |
// 该函数返回一个对象,包含你要暴露的属性 | |
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