一个功能中是否可以具有“ this”和“ return”?
像这样?

我经常用不同的参数调用该函数。但是据我了解严格模式,您必须使用“ new convertSomething”为每个参数启动函数。有没有更短的方法?
谢谢



"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>

最佳答案

即使这样做的原因值得怀疑,您也可以执行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);
}


编辑

另一个解决方案是:

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);
    }


然后,您可以为所有函数调用该函数:

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


编辑2

通常,类,函数,方法只能做一件事情。在创建API的情况下,将函数同时用作函数和构造函数可能会使使用它的人感到困惑。由于这些原因,我给您的第二个选择也许是最好的使用方法。

关于javascript - 严格模式下的“返回”和“此”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46707937/

10-13 00:40