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 methods
Rabbit.prototype.sayHello = function(){
console.log("hello, my name is " + this.getName());
}
Rabbit.prototype.checkP = function(){
this.check();
}
// Public static methods
Rabbit.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();
使用JavaScript的闭包&立即执行函数模拟静态变量
最新推荐文章于 2024-10-18 18:45:21 发布