将javascript变量声明为特定类型 [英] Declaring javascript variables as specific types

查看:170
本文介绍了将javascript变量声明为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切,但我会提供更多说明:

The title says it all, but I will provide more clarification:

看到许多javascript样本后,所有变量都被声明为类型 var ,并且看到对其他数据类型的支持,为什么不声明这样的特定数据类型的变量?意思是,为什么不是这个:

After seeing many samples of javascript where all variables are declared as type var, and seeing support for other datatypes, why aren't variables of a specific datatype declared as such? Meaning, why isn't this:

string hello ='Hello,World'

用于代替

var hello ='Hello,World'

查看 OReilly Javascript 显示其他类型的保留字。再次,为什么不使用它们?不会这样行: typeof(变量)==='string'; 不再需要?

Looking at sites like OReilly Javascript shows that there are reserved words for other types. Again, why aren't they used? Wouldn't it make lines like this: typeof(variable)==='string'; no longer needed?

推荐答案

很简单,JavaScript变量没有类型。 有类型。

Quite simply, JavaScript variables do not have types. The values have types.

该语言允许我们编写如下代码:

The language permits us to write code like this:

var foo = 42;
foo = 'the answer';
foo = function () {};

因此,在变量声明中指定类型是没有意义的,因为类型由变量的值。这在动态语言中相当常见。

So it would be pointless to specify the type in a variable declaration, because the type is dictated by the variable's value. This fairly common in "dynamic" languages.

这篇关于将javascript变量声明为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆