確かに、ベン。
この種のことは、JavaScriptのダイナミズムの根底にあります。まず、基本を見ていきます。たとえば、JavaやC ++ / C#などのクラスベースの言語を理解している場所から来ている場合、最も理にかなっているのはコンストラクターパターンです。これは非常に早い段階で含まれていました:
function Egg (type, radius, height, weight) {
// private properties (can also have private functions)
var cost = (type === "ostrich") ? 2.05 * weight : 0.35 * weight;
// public properties
this.type = type;
this.radius = radius;
this.height = height;
this.weight = weight;
this.cracked = false;
// this is a public function which has access to private variables of the instance
this.getCost = function () { return cost; };
}
// this is a method which ALL eggs inherit, which can manipulate "this" properly
// but it has ***NO*** access to private properties of the instance
Egg.prototype.Crack = function () { this.cracked = true; };
var myEgg = new Egg("chicken", 2, 3, 500);
myEgg.cost; // undefined
myEgg.Crack();
myEgg.cracked; // true
それは問題ありませんが、物事を回避するためのより簡単な方法がある場合があります。時々あなたは本当にクラスを必要としません。
必要なレシピはこれですべてなので、たまごを1つだけ使用したい場合はどうでしょうか。
var myEgg = {}; // equals a new object
myEgg.type = "ostrich";
myEgg.cost = "......";
myEgg.Crack = function () { this.cracked = true; };
それは素晴らしいことですが、そこにはまだ多くの繰り返しがあります。
var myEgg = {
type : "ostrich",
cost : "......",
Crack : function () { this.cracked = true; }
};
2つの「myEgg」オブジェクトはどちらもまったく同じです。
ここでの問題は、myEggのすべてのプロパティとすべてのメソッドが100%誰にでも公開されていることです。
その解決策は、すぐに呼び出す関数です。
// have a quick look at the bottom of the function, and see that it calls itself
// with parens "()" as soon as it's defined
var myEgg = (function () {
// we now have private properties again!
var cost, type, weight, cracked, Crack, //.......
// this will be returned to the outside var, "myEgg", as the PUBLIC interface
myReturnObject = {
type : type,
weight : weight,
Crack : Crack, // added benefit -- "cracked" is now private and tamper-proof
// this is how JS can handle virtual-wallets, for example
// just don't actually build a financial-institution around client-side code...
GetSaleValue : function () { return (cracked) ? 0 : cost; }
};
return myReturnObject;
}());
myEgg.GetSaleValue(); // returns the value of private "cost"
myEgg.Crack();
myEgg.cracked // undefined ("cracked" is locked away as private)
myEgg.GetSaleValue(); // returns 0, because "cracked" is true
それがまともなスタートであることを願っています。