function Test() {
var trulyPrivate = 42;
this.showTrulyPrivate = function() {
console.log("trulyPrivate = " + trulyPrivate);
};
}
Then trulyPrivate对于实例来说确实是私有的。成本是创建一个的成本showTrulyPrivate函数为each实例。 (函数对象也许能够共享底层代码,一个好的引擎会做到这一点,但是有will是单独的函数对象。)
总结一下:
var Test = (function() {
// Data and functions defined here are private to this code
// and shared across all instances. There is only one copy
// of these variables and functions.
var privateDataSharedByAll;
function privateFunctionSharedByAll() {
}
function Test() {
// Data and functions here are created for *each* instance
// and are private to the instance.
var trulyPrivate;
this.hasAccessToTrulyPrivate = function() {
// Has access to the shared private data *and* the
// per-instance private data.
};
}
return Test;
})();