I'm currently diving into Spine and I'm currently asking myself what would be the most elegant way to define a private function, using Spine's class creation method.
var PrinterManager = Spine.Class.create({
init: function () {
},
getAllAvailablePrinters: function () {
},
printDocument: function () {
}
});
(function () {
var instantiateActiveX = function(){
console.log("...");
}
PrinterManager.include({
pubInitActiveXPrinter: function(){
instantiateActiveX();
}
});
})();
A开发者_运维知识库s you can see I want instantiateActiveX
to be private and not visible to the outside. Using the JavaScript closure function trick, I can make it private without any problems, but this solution doesn't seem too elegant to me in the contest of creating classes like Spine does.
The code works, i.e. I can call PrinterManager.init().pubInitActiveXPrinter()
which will then internally call the private function and - correctly - I cannot call PrinterManager.init().instantiateActiveX()
.
My Question - Is there a more elegant way to do it with Spine that I didn't yet discover??
Well to put it simple, there's no way other than closures to make some function/variable invisible/private from the global scope.
No.
"private" functions don't exist. You only have local functions and closure state. And using local functions/variables and closures for state does not mix well with using prototypical inheritance.
The real question you should be asking is "why do you need private functions" because you don't.
If a function is unstable and shouldn't be used because the API might change just prepend it with _
var PrinterManager = {
...
_instantiateActiveX: function() {
...
}
}
If anyone uses these internal functions or variables then they have no right to complain when their code breaks if you change it.
精彩评论