JavaScript Has Built-In Mix-ins With ‘apply’ Or ‘call’

While I was running the Object-Oriented JavaScript discussion / demo at Pablo’s Fiesta this weekend, Jimmy Bogard asked me to try something fun. I had a small constructor function defined with a couple of methods defined directly in it.

I also had an object literal with no methods defined, and was showing something (I don’t remember what, at the moment). Jimmy asked me to call ‘apply’ on the constructor function and pass my object literal into it.

Then he asked me to call one of the methods from the function constructor on my object literal instance.

I expected this to fail, because I didn’t think the method would be around on my object literal. I was wrong, of course! Here’s that code running in a live JSFiddle (click the ‘result’ tab if you’re seeing the embedded version in this post).

CRAZY! … or… simply exposing how constructor functions actually work, exposing an easy way to do mixins with JavaScript?

Here’s what’s happening:

1) When I call the function using `apply`, the first parameter i used as the context of the call. Therefore, `this` inside of the function refers to the object that I’ve passed in to `apply`. When `this.someMethod = function(){…}` is called, ‘this’ is the object i passed in.

2) I’m allowed to add any function I want to any object I want at any time, simply by assigning the function to an attribute on the object. Therefore, when `this.someMethod = …` is called, it’s as if I was directly calling `foo.someMethod = …` directly.

With this in mind it seems that JavaScript has mix-ins built right in. There’s no need to use something like underscore.js’ `extend` method. But I wonder: are there any gotchas to this scenario? Anything that I need to watch our for? I’m going to have to play a little more to see what the effects are, what scenarios really work well and don’t, etc.

Adding A ‘has_image?’ Matcher To Capybara