Search code examples
javascriptangularjsvariable-assignmentmethod-chaining

Is it possible to use method chaining assigning strings in Javascript?


I want to use method chaining syntax using JavaScript and AngularJS. I assign arrays and strings.

This code works:

$mdDateLocaleProvider
     .shortDays = ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá']
     .msgCalendar = 'Calendario'
;

This code doesn't work:

$mdDateLocaleProvider
     .shortDays = ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá']
     .msgCalendar = 'Calendario'
     .msgOpenCalendar = 'Abrir calendario'
;

I think the msgOpenCalendar = 'Abrir calendario' sentence is failing due to the string assignment.

My solution:

$mdDateLocaleProvider
     .shortDays = ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá']
     .msgCalendar = 'Calendario'
;
$mdDateLocaleProvider
     .msgOpenCalendar = 'Abrir calendario'
;

Why is there a problem assigning a string but isn't with an array?


Solution

  • The name is method chaining for a reason, it is used to chain methods, not variable assignments.

    In method chaining, you are simply returning the object instance (of a mutable or a new immutable object) in the end of the method (function), so you can call the next function "right away".

    The reason it "works" is that an array in JS is an object, so you simply placed a msgCalendar property on the array that you assigned to shortDays property.

    Basically, what you achieved is:

    var shortDays = ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'].msgCalendar = 'Calendario';
    // here shortDays actually equals to 'Calendario', because it is like writing a = b = 2.
    $mdDateLocaleProvider.shortDays = shortDays;
    $mdDateLocaleProvider.msgOpenCalendar = 'Abrir calendario';