Do not modify context even using a function that modifies the context

Maybe the title sounds a little bit weird (please improve it) -- but I need a solution for the following scenario. I have the following code:

var Foo = function () {
    this._hello = "world!";
}; = function () {

var f = new Foo();; // => "world!"; // => undefined

I know that apply changes the context, so inside of bar, this will be the global object (at the second call).

But what I need is to access this from Foo function. A solution that I see would be:

var Foo = function () {
   var self = this;
   self._hello = "world!"; = function () {

However, I would choose not to have method declarations inside of another function.

I'd prefer to define methods same column level (just for code style):

var Foo = ...;
Foo.prototype.method = ...;

Is this possible? How?


You can use the bind() method to tackle these kinds of problems. Instead of something.method( call something.method( to get the bar method always called on the expected context (f).

If you don't want to use bind in every location where you pass bar around as a callback, you can also put it in the constructor to create a dedicated bound function for every instance by default:

function Foo() {
    this._hello = "world!"; =;
} = function () {

var f = new Foo;
something.method(; // works!

Need Your Help

Modelling / documenting functional programs

functional-programming clojure uml modeling

I've found UML useful for documenting various aspects of OO systems, particularly class diagrams for overall architecture and sequence diagrams to illustrate particular routines. I'd like to do the...