我在jsFiddle中设置了一个小测试来演示显示对象模式是多么美妙的事情:
var Test = (function(){
var priv = "Banana";
var public = "Orange";
var pubobj = {name:"Cheese"};
function constructor(){
this.public = public;
this.pubobj = pubobj;
this.instance = {name:"Grape"};
this.instanceMethod = function(){
return priv;
};
};
constructor.prototype.private = function(){
return priv;
};
return constructor;
})();
var myTest = new Test();
console.log(myTest.public); //Orange
console.log(myTest.priv); //undefined
console.log(myTest.private()); //Banana
var myTest2 = new Test();
console.log(myTest.public === myTest2.public); //true (they are both primitives with the same value)
console.log(myTest.private === myTest2.private); //true (the methods share the same instance)
myTest.public = "cheese";
console.log(myTest.public, myTest2.public); // "cheese", "Orange" (overwriting the primitive doesn't change the primitive of myTest2)
myTest.pubobj.name = "Melon";
console.log(myTest.pubobj, myTest2.pubobj); //the name property for both is now "Melon" (both test objects share the same instance of pubobj)
myTest.instance.name = "Raspberry";
console.log(myTest.instance, myTest2.instance); // the name of myTest2.instance is unchanged
console.log(myTest.instanceMethod === myTest2.instanceMethod); // false (while identical, these methods have separate instances)