当然,本。
这种方式触及了 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
这很好,但有时有更简单的方法来解决问题。有时你真的不需要上课。
如果你只是想用一个鸡蛋怎么办,因为这就是你的食谱所要求的?
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; }
};
这两个“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
希望这是一个不错的开始。