Here\'s a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).
function Example() {
function privateFun
It is worth understanding how the value of this
in javascript is determined in addition to just having someone tell you a code fix. In javascript, this
is determined the following ways:
If you call a function via an object property as in object.method()
, then this
will be set to the object inside the method.
If you call a function directly without any object reference such as function()
, then this
will be set to either the global object (window
in a browser) or in strict mode, it will be set to undefined
.
If you create a new object with the new
operator, then the constructor function for that object will be called with the value of this
set to the newly created object instance. You can think of this as the same as item 1 above, the object is created and then the constructor method on it is called.
If you call a function with .call()
or .apply()
as in function.call(xxx)
, then you can determine exactly what this
is set to by what argument you pass to .call()
or .apply()
. You can read more about .call() here and .apply() here on MDN.
If you use function.bind(xxx)
this creates a small stub function that makes sure your function is called with the desired value of this
. Internally, this likely just uses .apply()
, but it's a shortcut for when you want a single callback function that will have the right value of this
when it's called (when you aren't the direct caller of the function).
In a callback function, the caller of the callback function is responsible for determining the desired value of this
. For example, in an event handler callback function, the browser generally sets this
to be the DOM object that is handling the event.
There's a nice summary of these various methods here on MDN.
So, in your case, you are making a normal function call when you call privateFunction()
. So, as expected the value of this
is set as in option 2 above.
If you want to explictly set it to the current value of this
in your method, then you can do so like this:
var Example = (function() {
function Example() {
function privateFunction() {
// "this" is window when called.
console.log(this);
}
this.publicFunction = function() {
privateFunction.call(this);
}
}
return Example;
})();
ex = new Example;
ex.publicFunction();
Other methods such as using a closure and defined var that = this
are best used for the case of callback functions when you are not the caller of the function and thus can't use 1-4. There is no reason to do it that way in your particular case. I would say that using .call()
is a better practice. Then, your function can actually use this
and can behave like a private method which appears to be the behavior you seek.