<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js——private 私有方法公有化</title> </head> <body> <script> /* 假設咱們定義了一個函數,但並不想讓外界修改它,因而將其設爲私有。但有時候我 們又但願讓某些外部代碼能訪問到它,這該如何實現呢?解決方案是將這個私有函數賦值 給一個公有屬性 * */ var MYAPP = {}; MYAPP.dom = (function () { var _setStyle = function (el, prop, value) { console.log('setStyle'); }; var _getStyle = function (el, prop) { console.log('getStyle'); }; // 把私有方法給一個公有屬性 return { setStyle: _setStyle, getStyle: _getStyle, yetAnother: _setStyle } }()); // MYAPP.dom.setStyle 指向的是新的方法; MYAPP.dom.setStyle = function(){console.log('b');}; MYAPP.dom.setStyle() // 打印 b MYAPP.dom.yetAnother() // 打印私有setStyle </script> </body> </html>