I’m trying something like this:
(function() {
var Foo, foo;
Foo = function(proto) {
var obj, privateMethod, publicMethod;
privateMethod = function() {
return console.log("private", this);
};
publicMethod = function() {
console.log("public", this);
return privateMethod();
};
obj = Object.create(proto);
obj.bar = publicMethod;
return obj;
};
foo = new Foo({
baz: "dooz"
});
foo.bar();
}).call(this);
Obviously this is the object itself when publicMethod is called, but is set to the global object in the privateMethod. I know it can be solved by changing:
return privateMethod();
to:
return privateMethod.call(this);
I know that this get’s lost when a function is nested in a function, but did not expect that case here. Do I encounter this JavaScript bug here or is there something that I simply do not understand yet?
Context (
this), in javascript, is set by how a function is called, and is in no way a property of the function itself.What this example shows us is that the the dot syntax there sets
this. Think ofobj.bar()is syntax sugar forobj.bar.call(obj).So your public method gets the right
this, because of how it’s called in external code.But your private method is invoked with no receiver at all.
So no context is assigned, and it defaults to the global object.
So given you are creating these functions in the constructor, you have some flexibility.
You could assign the proper value of
thisin the constructor to something else, and use that in your private functions. (Likely the best option)Or if your JS target engine support
Function.prototype.bind(not all do, sadly) you could do:Which will return a function that has an assigned context, no matter what.
Or you could bind it manually yourself.