I'm reading JavaScript - The Good Parts currently. So I've dealing with augmentation of types. I understand the motivation and the implementation. But if I look at the code ...
Function.prototype.method = function(ident, funct) {
    this.prototype[ident] = funct;
    return this; // No idea. For what?
};
... then I don't understand the purpose of the return. I have put the return in comments. That doesn't have an effect. It functioned anyway.
My complete code:
Function.prototype.method = function(ident, funct) {
    this.prototype[ident] = funct;
    return this;
};
Date.method('sayHello', function() {
    alert(new Date().toString());
});
var myDate = new Date();
myDate.sayHello();
So what it is for?
Typically this is done so you can chain method calls, so called "fluent interfaces":
obj.method().anotherMethod().yetAnotherMethod()
E.g.:
'string'.toUpperCase().substr(2).repeat(3)
In case of the string, another new string is being returned instead if this, but you get the idea why it's useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With