I thought that functions created using .prototype were supposed to be able to access local variables. Here is what I’m talking about:
function obj() {
var a = "String";
this.innerPrint = function() {
document.write("<p>" + a + "</p>");
};
}
obj.prototype.outerPrint = function() {
document.write("<p>" + a + "</p>");
};
var inst = new obj();
inst.innerPrint();
inst.outerPrint();
What I thought would happen is that both of these functions would do the same thing. But what actually happened is outerPrint doesn’t have access to the variable a. Could someone explain to me how you get locals in a prototype function.
Here is a fiddle running this code:
http://jsfiddle.net/Wryte/mxXzg/
By the way, I want to use prototype functions because then each instantiation of the object doesn’t have a copy of the function but they each point to the same one.
Of course not, you cannot access one function’s locals from another function defined outside the first. It does not matter if the second is defined in the prototype property of the first. Each invocation of your
objfunction defines a new localavariable, so you cannot avoid having separate copies of the function that needs to access it.I assume you actually require that variable to be a local and not an instance property, so one possible approach would be to have only a thin local wrapper around your function:
Again, I assume you have a more complex function in place of
outerPrint, so this way you can avoid the duplication of a large function at the expense of duplication of a minimal wrapper. This way you retain the privateness of theavariable, while a public getter would allow external code to inspect its value.UPDATE: On @Bergi’s remark, I’ve modified the code to make
outerPrinta local function in the same scope where theobjconstructor is defined. No longer being on the prototype, it will not be directly callable forobjinstances. Note that all of the code will need to be inside a function scope, in order to avoid a globalouterPrintfunction.