使用JavaScript的闭包&立即执行函数模拟静态变量

来源:互联网 发布:股票数据猫网 编辑:程序博客网 时间:2024/06/06 02:33
var Rabbit = (function(){    //Private static attrbutes    var rabbitNum = 0;    return function(myName,myFaveriteFood,myAddress){        // Private attributes        var name, food, address;        // Private method        function checkPassword(){            console.log("password:123");        }         // Privileged methods        this.setName = function(newName){            name = newName;        }        this.getName = function(){            return name;        }        this.setFood = function(newFood){            food = newFood;        }        this.getFood = function(){            return food;        }        this.setAddress = function(newAddress){            address = newAddress;        }        this.setAddress = function(){            return address;        }        this.check = function(){            checkPassword();        }        rabbitNum++;        this.seeNumber = function(){            console.log("rabbitNum="+rabbitNum);        }        //init        this.setName(myName);        this.setFood(myFaveriteFood);        this.setAddress(myAddress);    }})();// Public methodsRabbit.prototype.sayHello = function(){    console.log("hello, my name is " + this.getName());}Rabbit.prototype.checkP = function(){    this.check();}// Public static methodsRabbit.eatBreakfast = function(){    console.log("all rabbits are eating");}var rabbit = new Rabbit("Emily","apple","Earth");var rabbit2 = new Rabbit("Hellen","water melon","Earth");rabbit.sayHello();rabbit.seeNumber();Rabbit.eatBreakfast();
0 0
原创粉丝点击