JavaScript 中的类型转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31196396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type casting in JavaScript
提问by Matthew Layton
Example:
例子:
function action(value) {
// I want to operate on a string
String(value)...;
}
When we pass dynamic values into JavaScript's primary types (String
, Number
, Boolean
, Object
, etc.) we can (for want of a better word) cast the value to the specified type.
当我们将动态值传递给 JavaScript 的主要类型(String
、Number
、Boolean
、Object
等)时,我们可以(为了更好的词)将值转换为指定的类型。
Is it possible to build this feature in custom types, and how would I go about this?
是否可以在自定义类型中构建此功能,我将如何处理?
Example of what I would like to do:
我想做的例子:
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***
}
Is it possible to call constructor functions in this way and have the constructor function "cast" the value to an instance of itself - or does this only work for JavaScript's primary types?
是否可以以这种方式调用构造函数并让构造函数将值“转换”为自身的实例 - 或者这仅适用于 JavaScript 的主要类型?
采纳答案by jfriend00
Your custom constructor can just examine the typeof
the arguments that it is passed and behave accordingly. This isn't technically a "cast", but rather writing code to examine the types of the arguments and then decide on the proper behavior which can include converting from one type to another.
您的自定义构造函数可以只检查typeof
它传递的参数并相应地进行操作。这在技术上不是“强制转换”,而是编写代码来检查参数的类型,然后决定正确的行为,包括从一种类型转换为另一种类型。
See How to overload functions in javascript?for a much longer description of how to examine arguments sent to any function and then adjust the behavior of the function based on the type and position and presence of the arguments. This same functionality can be used to do something that is "cast" like (though we don't usually think of casting in Javascript, but rather just converting).
请参阅如何在 javascript 中重载函数?有关如何检查发送到任何函数的参数,然后根据参数的类型、位置和存在情况调整函数的行为的详细说明。这个相同的功能可以用来做一些“强制转换”之类的事情(虽然我们通常不考虑在 Javascript 中进行强制转换,而只是转换)。
We could give you actual code examples if you can be more specific about what types you want to "cast" in your Point constructor.
如果您可以更具体地了解要在 Point 构造函数中“强制转换”的类型,我们可以为您提供实际的代码示例。
There are some simple examples of "cast" like things:
有一些简单的“演员”之类的例子:
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);
}
Or, a little more interesting example that can take a number of ms, a string with units at the end or an object with properties:
或者,还有一个更有趣的例子,它可以使用多个毫秒、一个以单位结尾的字符串或一个具有属性的对象:
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});
回答by ZEE
If you are serious about type enforcing (and there is a lot of good reasons to be)... and you want to continue to use Javascript... maybe you should give a try to TypeScript
如果您认真对待类型强制(并且有很多充分的理由)……并且您想继续使用 Javascript……也许您应该尝试一下 TypeScript
It enforces type checking and compiles down to Javascript Which gives you the option to publish the TypeScript for inline compilation...
它强制执行类型检查并编译为 Javascript,这使您可以选择发布用于内联编译的 TypeScript...
Or if you intent a bit for your work (like me)... you can develop a project and spit-out the Javascript before uploading... in this phase you can optimize the 'thing'... pass a Linter, a Minifier and a Obfuscator... and you'll get highly optimized and a bit protected piece of code (if we are talking about client-side of course, at server side no obfuscation is advised).
或者,如果你对你的工作有点意图(像我一样)......你可以开发一个项目并在上传之前吐出 Javascript......在这个阶段你可以优化'东西'......通过一个 Linter,一个Minifier 和 Obfuscator ......你会得到高度优化和一些受保护的代码(当然,如果我们谈论的是客户端,则在服务器端不建议进行混淆)。
Another BIG-BIG-BIG advantage (to me at least) is that you can use the best Intellitype/Intellisense/Refactor IDE (VS 2013R4 CE) which is free.
另一个 BIG-BIG-BIG 优势(至少对我而言)是您可以使用免费的最好的 Intellitype/Intellisense/Refactor IDE (VS 2013R4 CE)。
See here the last features in TypeScript... TypeScript at Build/2014 by Anders Hejlsberg (channel9)
请在此处查看 TypeScript 中的最后一个功能... TypeScript at Build/2014 by Anders Hejlsberg (channel9)
ZEE
ZEE