javascript - JavaScript 中的类型转换

标签 javascript oop casting ecmascript-5

示例:

function action(value) {
     // I want to operate on a string
     String(value)...;
}

当我们将动态值传递给 JavaScript 的主要类型(StringNumberBooleanObject 等)时.) 我们可以(需要一个更好的词)将值转换为指定的类型。

是否可以在自定义类型中构建此功能,我将如何着手?

我想做的事的例子:

function action(value) {
    Point(value)...;
    // Value at this point (excuse the pun) is a point
    // // *** Would like to see that intellisense is aware of the type at this point, but please don't assume this is ONLY for intellisense***
}

是否有可能以这种方式调用构造函数并让构造函数将值“转换”为它自己的一个实例——或者这是否只适用于 JavaScript 的主要类型?

最佳答案

您的自定义构造函数可以只检查 typeof 它传递的参数并相应地运行。这在技术上不是“转换”,而是编写代码来检查参数的类型,然后决定适当的行为,包括从一种类型转换为另一种类型。

参见 How to overload functions in javascript?有关如何检查发送到任何函数的参数,然后根据参数的类型、位置和存在来调整函数行为的更长描述。同样的功能可用于执行类似于“强制转换”的操作(尽管我们通常不认为在 Javascript 中进行强制转换,而只是转换)。

如果您可以更具体地说明要在 Point 构造函数中“转换”的类型,我们可以为您提供实际的代码示例。

有一些简单的“cast”例子:

function delay(fn, t) {
    // if t is passed as a string represeantation of a number, 
    // convert it to an actual number
    return setTimeout(fn, +t);
}

或者,一个更有趣的例子,可以采用毫秒数,一个在末尾带有单位的字符串或一个带有属性的对象:

function delay(fn, t) {
    var typeT = typeof t, ms, matches, num, multiplier,
        suffixes = {ms: 1, sec: 1000, min: 1000 * 60, hr: 1000 * 60 * 60};
    if (typeT === "string") {
        matches = t.match(/^([\d.]+)(.+)$/);
        if (matches) {
            num = +matches[1];
            multiplier = suffixes[matches[2]];
            if (multiplier) {
                ms = num * multiplier;
            }
        }
    } else if (typeT === "number") {
        // plain number is milliseconds
        ms = t;
    } else if (typeT === "object" && t.units && t.value) {
        multiplier = suffixes[t.units];
        if (multiplier) {
           ms = t.value * multiplier;
        }            
    }
    if (ms === undefined) {
        throw new Error("Invalid time argument for delay()");
    }
    return setTimeout(fn, ms);
}


delay(myFn, "2.5hr");
delay(myFn, "25sec");
delay(myFn, 150);
delay(myFn, {units: "sec", value: 25});

关于javascript - JavaScript 中的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196396/

相关文章:

javascript - 有条件地更新 React Json 值

javascript - 如何使用 oboe 迭代对象数组?

matlab - 从Matlab中一个类的所有实例中检索属性,将值写入文件

c++ - 不要在类内部使用类成员函数

oop - 面向对象建模与面向对象编程有何不同?

c++ - 指针变量在数组内使用float计算平均值C++

JavaScript 点

Java 转换 : Which is better -- the imperative or programmatic way?

c - 在连接到服务器之前尝试编译客户端时出错

javascript - Angular 2 : how to implement image map area