Grammar and types

本贴最后更新于 3447 天前,其中的信息可能已经东海扬尘

声明方式

There are three kinds of declarations in JavaScript.

var
Declares a variable, optionally initializing it to a value.
let
Declares a block scope local variable 块范围的局部变量, optionally initializing it to a value.
const
Declares a read-only named constant.

声明一个变量

You can declare a variable in three ways:

  • With the keyword {{jsxref("Statements/var", "var")}}. For example, var x = 42. This syntax can be used to declare both local and global variables.
  • By simply assigning it a value. For example, x = 42. This always declares a global variable 全局变量 and cannot be changed at the local level. It generates a strict JavaScript warning. You shouldn't use this variant.
  • With the keyword {{jsxref("Statements/let", "let")}}. For example, let y = 13. This syntax can be used to declare a block scope local variable 块范围的局部变量. See Variable scope below.

计算变量的值

A variable declared using the var or let statement with no initial value specified has the value {{jsxref("undefined")}}.

使用var还是没有初始值的let声明,默认值都是undefined

An attempt to access an undeclared variable will result in a {{jsxref("ReferenceError")}} exception being thrown:

访问没有声明的变量会抛异常

var a;
console.log("The value of a is " + a); // logs "The value of a is undefined"
console.log("The value of b is " + b); // throws ReferenceError exception
 

You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.

var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}
 

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined:

var myArray = [];
if (!myArray[0]) myFunction();
 

The undefined value converts to NaN when used in numeric context. undefined作为布尔值是false,作为数字是NaN

var a;
a + 2 = NaN

When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts.

For example: 而null作为布尔值是false,作为数字是0

var n = null;
console.log(n * 32); // Will log 0 to the console
 

变量作用域

When you declare a variable outside of any function, it is called a global variable 函数以外的都是全局变量, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

JavaScript before ECMAScript 6 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement. 同一个函数内都可以访问

if (true) {
  var x = 5;
}
console.log(x);  // 5
 

This behavior changes, when using the let declaration introduced in ECMAScript 6. 但let声明的是块范围

if (true) {
  let y = 5;
}
console.log(y);  // ReferenceError: y is not defined

Variable hoisting

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined声明的位置无所谓,放在最后也可以,但同样要初始化

/**
 * Example 1
 */
console.log(x === undefined); // logs "true" 
var x = 3;

/**

  • Example 2
    */
    // will return a value of undefined
    var myvar = "my value";

(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();

 

The above examples will be interpreted the same as:

/**
 * Example 1
 */
var x;
console.log(x === undefined); // logs "true"
x = 3;

/**

  • Example 2
    */
    var myvar = "my value";

(function() {
var myvar;
console.log(myvar); // undefined 虽然声明了但没初始化
myvar = "local value";
})();

 

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code. 尽量把所有的var声明都放在函数最上面,这样能更清晰

 

全局变量

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

可以指定另一个window或iframe的名字来访问全局变量

常量

You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

const prefix = '212';

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

常量的名字不能跟函数名或其他变量名相同

// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
const g = 5;
var g;

//statements
}

 

 

  • JavaScript

    JavaScript 一种动态类型、弱类型、基于原型的直译式脚本语言,内置支持类型。它的解释器被称为 JavaScript 引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在 HTML 网页上使用,用来给 HTML 网页增加动态功能。

    728 引用 • 1273 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...