欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js, javascript, 闭包, 立即执行函数

程序员文章站 2022-07-15 14:27:15
...

目的:学习 闭包,立即执行函数

概要:类型二,因使用立即函数,new新对象时,变量[counter_gad]未初始化。此与类型一不同点!!

 

类型一:

        var closureMode = function () {
        var countNo = 0;
        return function (){
            return (countNo += 1);
        };
        };
        
        var closureOne = new closureMode();
        console.log("1.closureOne.countNo:" + closureOne.countNo); // undefined
        console.log("2.closureMode.countNo:" + closureMode.countNo); // undefined
        console.log("3.closureOne:" + closureOne()); // 1
        console.log("4.closureOne:" + closureOne()); // 2
        
        var closureTwo = new closureMode();
        console.log("1.closureTwo:" + closureTwo()); // 1
        console.log("2.closureTwo:" + closureTwo()); // 2
        

 

类型二:

        var Gadget = (function () {
            var counter_gad = 0;
            
            NewGadget = function () {
                // counter_gad += 1;
            };
            
            NewGadget.prototype.getCounter = function () {
                return counter_gad += 1;;
            };
            
            return NewGadget;
        }()); // 立即执行函数。
        
        var g1 = new Gadget();
        utilTemp.log("g1.getCounter():" + g1.getCounter()); // 1
        utilTemp.log("g1.getCounter():" + g1.getCounter()); // 2
        
        var g2 = new Gadget();
        utilTemp.log("g2.getCounter():" + g2.getCounter()); // 3