12.21.06
JS call and apply need your love, too
After my ‘watch()’ post, Frozen O pointed out that call and apply need the love, too. The great thing about Javascript is that you can construct classes out of useful functions, then reuse these functions for other classes. Just to make the point, I used ‘this’ to show that the function really does become owned by the calling function.
function show_state(yes_or_no) {
if(yes_or_no) {
document.writeln(”State is “+ this.state);
} else {
document.writeln(”State is not “+ this.state);
}
}
function Puppies(temperature) {
this.state = temperature;
show_state.call(this, true);
show_state.apply(this, new Array(true));
}function Happiness(mood) {
this.state = mood;
show_state.call(this, true);
show_state.apply(this, new Array(false));
}
var puppy = new Puppies(”warm”);
var marriage = new Happiness(”bliss”);
Result:
State is warm State is warm State is bliss State is not bliss