Augmented implementation in JavaScript

来源:互联网 发布:远程数据库导入sql文件 编辑:程序博客网 时间:2024/04/27 14:06
For js, usually use augmented implementation for function as follows (self execute), the advantage are: if you function has a calculator function, and third party also has a calculator function, the calculator will include all the functions both from yours and third party. In the following code, the calculator will finally have 5 functions. When calculator is loaded for the first time, it will pass "{}" as argument because window.calculator is null, for the second time and then on, it will pass "window.calculator" as argument. If you want to let other places outside that function to use the variables or functions, you must return those variables or functions as object.
 var calculator = (function (math) {     math.add = function (a, b) {        return a + b;     };       math.subtract = function (a, b) {        return a - b;     };       math.multiply = function (a, b) {        return a * b;     };       math.divide = function (a, b) {        return a / b;     };       return math;  })(window.calculator || {});    var calculator = (function (math) {     math.doubled = function (a, b) {        return (a + b) * 2;     };       return math;  })(window.calculator || {});  

原创粉丝点击