Skip to content

Instantly share code, notes, and snippets.

@MiaoziYu
Created September 23, 2015 09:28
Show Gist options
  • Select an option

  • Save MiaoziYu/b364b74f18c19a2c52d1 to your computer and use it in GitHub Desktop.

Select an option

Save MiaoziYu/b364b74f18c19a2c52d1 to your computer and use it in GitHub Desktop.
js private and public
var isHungry = true;
var mzApp = (function(isHungry) {
// 此处为private,它不能被外部访问,但可以被namespace内部使用
var foodStore = ["cake", "fish", "meat", "icecream"];
// 此处为public
return {
food: [],
people: [
{name: "miaozi", myFood: ""},
{name: "happyCat", myFood: ""},
{name: "happyDog", myFood: ""}
],
buyFood: function (idx) {
this.food.push(foodStore[idx]);
},
feedPeople: function(idx) {
if (this.food.length > 0 && isHungry) {
this.people[idx].myFood = this.food.pop();
console.log(this.people[idx].name + " said: I ate " + this.people[idx].myFood + ". Thanks:) I'm happy now!");
} else if (this.food.length === 0){
console.log("Sorry, there is no food in storage");
} else if (!isHungry) {
console.log("I'm not hungry! please do not feed me!")
}
}
};
})(isHungry);
// 因为foodStore是private,所以外部无法访问它
mzApp.foodStore; // undefined
// 而其他public的东西则可以轻松使用
mzApp.buyFood(1);
mzApp.food; // ["fish"]
mzApp.feedPeople(0); // miaozi said: I ate fish. Thanks:) I'm happy now!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment