Search code examples
javascriptthisstrict

"return" and "this" in strict-mode


is it possible to have "this" and "return" in one function? Like this?

I call the function often with different parameters. But as I understand strict mode, you have to initiate the function for every parameter with "new convertSomething". Is there a shorter way? Thanks

"use strict";

function convertSomething(convertSeconds){
    let minutes = Math.floor(convertSeconds / 600) % 600;
    let seconds = Math.trunc(convertSeconds % 600 / 10);
    let milliseconds = (convertSeconds % 600)%10;

    this.milliseconds = milliseconds;
    this.minutes = minutes;
    this.seconds = seconds;

    let formattedTime = minutes + ":" + seconds + "." + milliseconds;
    this.formattedTime = formattedTime;
    return formattedTime;
}

let showTime = new convertSomething(2005);

console.log(showTime.milliseconds);
console.log(showTime.formattedTime);
console.log(convertSomething(1000)); // ERROR: this is undefined
<html>
    <head>
        <meta charset="ISO-8859-1">
        <script src="returnthis.js"></script>
    </head>
    <body>
        
    </body>
</html>


Solution

  • Even if the reason for doing that is questionable, you can do this :

    function convertSomething(convertSeconds){
        let minutes = Math.floor(convertSeconds / 600) % 600;
        let seconds = Math.trunc(convertSeconds % 600 / 10);
        let milliseconds = (convertSeconds % 600)%10;
        let formattedTime = minutes + ":" + seconds + "." + milliseconds;
        if(this){
           this.milliseconds = milliseconds;
           this.minutes = minutes;
           this.seconds = seconds;
           this.formattedTime = formattedTime;
        }
        return(formattedTime);
    }
    

    EDIT

    Another solution would be this one:

    function convertSomething(convertSeconds,details){
            let minutes = Math.floor(convertSeconds / 600) % 600;
            let seconds = Math.trunc(convertSeconds % 600 / 10);
            let milliseconds = (convertSeconds % 600)%10;
            let formattedTime = minutes + ":" + seconds + "." + milliseconds;
            if(details){
               details.milliseconds = milliseconds;
               details.minutes = minutes;
               details.seconds = seconds;
               details.formattedTime = formattedTime;
            }
            return(formattedTime);
        } 
    

    Then you can call the function for everything:

    var time = convertSomething(2500);
    var details = {};
    var time2 = convertSomething(1000,details);
    console.log(details.minutes) // or anything else
    

    EDIT 2

    Generally, class, functions, methods are meant to do one and only one thing. In the case you were creating an API, using a function both as a function and a constructor can be very confusing for someone using it. For those reasons, the second option I gave you maybe the best approach to use.