Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Augmenting types - Purpose of "return this" [duplicate]

Tags:

javascript

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?

like image 317
cluster1 Avatar asked Apr 16 '15 08:04

cluster1


1 Answers

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.

like image 50
deceze Avatar answered Oct 20 '22 20:10

deceze