Created
July 16, 2017 14:10
-
-
Save t301000/789538d2de163f5e5aec5eeef3e8398d to your computer and use it in GitHub Desktop.
請利用 JS 閉包 (Closure) 特性實作私有變數的 get 與 set 存取子
This file contains 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
/* | |
請依據以下範本撰寫一個 MyFunc 函式: | |
function MyFunc() { | |
// YOUR CODE HERE | |
} | |
撰寫完成後,必須可以正常執行以下程式碼: | |
var o = MyFunc(); | |
o.get_a() // 回傳 undefined | |
o.set_a(3); | |
o.get_a(); // 回傳 9 | |
o.set_a(4); | |
o.get_a(); // 回傳 16 | |
o.get_b() // 回傳 0 | |
o.set_b(99); | |
o.get_b(); // 回傳 99 | |
*/ | |
function MyFunc() { | |
var a, b = 0; | |
return { | |
set_a: function(v) { | |
a = v * v; | |
}, | |
get_a: function() { | |
return a; | |
}, | |
set_b: function(v) { | |
b = v; | |
}, | |
get_b: function() { | |
return b; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment