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!";
};

Foo.prototype.bar = function () {
    console.log(this._hello);
};

var f = new Foo();
f.bar(); // => "world!"
f.bar.apply(this); // => 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!";
   self.bar = function () {
      console.log(self._hello);
   };
};

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?

Answers


You can use the bind() method to tackle these kinds of problems. Instead of something.method(f.bar) call something.method(f.bar.bind(f)) 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!";
    this.bar = this.bar.bind(this);
}
Foo.prototype.bar = function () {
    console.log(this._hello);
};

var f = new Foo;
something.method(f.bar); // 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...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.