I liked it.
I always thought of JavaScript development as painful; a sort of necessary evil. Turns out there's an obscenely powerful language there, if you go looking for it (incidentally, start by looking here). Among those powerful features are first-class functions. For example, suppose I run the following code:
var greeter = { name: 'Mike', greet: function() { return 'hello ' + this.name; } }; greeter.greet(); // -> 'hello Mike'
Nothing shocking there, right? Well, I can actually reach into the greeter object and steal the greet function:
var greet = greeter.greet; greet(); // -> 'hello '
Okay, kind of cool, but not quite the expected result. Where did my name go? When you grab a function that references this and invoke it, you need to tell JavaScript what context you want to execute it in. The built-in JavaScript Function object has a method called apply which lets you set the value of this (it also lets you pass an argument array if you want to):
var bob = { name: 'Bob' }; greet.apply(bob); // -> 'hello Bob'
This is called the apply invocation pattern. What can you do with it? That'll have to wait for another post...
No comments:
Post a Comment