I have following setup. method and method1 both are public methods of class Student. But why ca only “method” access private variable p
function Student() {
var p = 10;
this.method = function() {
document.write(p);
};
};
Student.prototype.method1 = function() {
document.write('here');
document.write(p);
};
var s = new Student();
s.method();
s.method1();
How does it make sense, I mean is it “a public method that does not have access to private members!”
There is no magic going on with JavaScript’s prototypal inheritance.
Studentis still a function andpis local to that function. It cannot be accessed from outside code in any way.methodcan accesspbecause it is defined insideStudentand therefore forms a closure, butmethod1is declared outsideStudent‘s scope.Assigning a function to another function’s prototype cannot give it access to its local variables.
Consider this example:
You might think that because
foois invoked as an object method it could have access to the local variables, but that’s just not the case. The only value that is determined dynamically isthis, it is a special keyword. All other variables are strictly defined through the scope chain.