Declaring javascript variables as specific types [closed]

喜你入骨 提交于 2019-11-27 17:16:34

问题


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

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'

used instead of

var hello = 'Hello, World'

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?


回答1:


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.



来源:https://stackoverflow.com/questions/14202743/declaring-javascript-variables-as-specific-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!