In my own answer for A JavaScript VM that interprets code written in JSON I stated that the "public" properties of a JavaScript closure cannot be accessed in a "private" function.
The example given in that post is
function anobject(){
var privatefunction = function(){
//publicfunction(); //wrong; you have no access to it
console.log(this); //refer to the global object, not the object creating
};
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
I think the reason is for some backward compatibility issues privatefunction
must belong to the global object. So the public function is only an anonymous function that assigned to a property of this
. This explains why calling publicfunction
will fail because it need to have a reference to this
first.
However, the following fix is still not work:
function anobject(){
var privatefunction = function(){
//publicfunction(); //wrong; you have no access to it
console.log(this); //refer to the object creating
}.bind(this);
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
As I explicitly specify that privatefunction
should be bound with the object creating, calling publicfunction
should work but it does not. I have to do the following:
function anobject(){
var privatefunction = function(){
this.publicfunction();
console.log(this); //refer to the object creating
}.bind(this);
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
Another workaround (the way that I am using) is the following:
function anobject(){
var privatefunction = function(){
publicfunction();
console.log(this); //refer to the object creating
};
var publicfunction = function(){
console.log(this); //refer to the object creating
}
this.publicfunction = publicfunction;
}
Now is the question part. What is the reason behind this behavior? What is it trying to avoid by disabling access this
's properties without explicit specification?
UPDATE: the main part of the question is : When the interpreter cannot find a name in the scope chains, why should'nt it have a look at the this
properties?