学习JS的心路历程-声明

变量

在程序中将一个值指定(assign)给一个符号式的容器(symbolic container),叫做一个变量(variable)。

声明
在JS中目前提供了三种声明方式:

var

声明一个变量,可选择是否给予一个初始值。

作用范围(scope)于该函式之内;但是如果在函式外声明,其作用范围则为全局性(global)。

var price = 10;

price = price * 2;

console.log(price);

let(ES6新增)

声明一个内存块范围(scope)内的本地变量,可选择是否给予一个初始值。

let prices = 10;

if(prices === 10){

let prices = 20;

console.log(prices);// 20

}

console.log(prices);// 10

const(ES6新增)

声明一个只能读取内存块范围(scope)内的本地变量。

const price = 10;

console.log(price);//10

price = 20;//Uncaught TypeError: Assignment to constant variable.

如果在声明时候未给予值,JS会预设为undefined(除了const)

var a;

console.log(a)//undefined

let b;

console.log(b)//undefined

const c;

//Uncaught SyntaxError: Missing initializer in const declaration

命名规则

在命名时候需要注意下面几点规则:

开头不能数字

英文大小写是有区分的

不可使用保留字元

在MDN中有列出了哪些是JS的保留字元。

函式

程序拆解成可重复使用的片段

具名代码片段(a named section of code)可以藉由名称来呼叫执行。

可选择是否接受参数(arguments即参数(parameters))

声明
函式由三个关键字组成,依序是:

名称

参数列表

大括号{}

这边举个例子:

function totalPrice(number,price){

return number*price

}

totalPrice(2,20)

函式totalPrice使用了两个参数number和price,两着相乘后透过return回传其值。

函式通常会有回传值,但并非每种函式都需要回传值,也有可能利用输出的方式来输出结果。

function totalPrice(number,price){

console.log(number*price)

}

totalPrice(2,20)//40

在声明函式时可以选择不撰写名称,这将会使函式成为一个匿名函式,通常作为一个指定值,指定给一个变量后,该变量便成为了这个匿名函式的名称。

var total = function(number,price){

console.log(number*price)

}

total(2,20)//40

以函式作为参数传入

在JS中也能将函式做完参数传入到另一个函式,而且在函式的最后也可以回传函式。这种函式的结构称之为高阶函式(Higher-order function)。我们常听到的callback就是高阶函式的应用,不过这会在很后面才提到。在这边只需要了解函式也能当作参数即可。

var total = function(count,fn){

return fn(count)

}

var price = function(count){

return count * 20

}

console.log(total(10,price))//200

参考资料:

变量、常数与命名

https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part3/function_scope.html

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Functions

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements

猜你喜欢

转载自www.cnblogs.com/lannyQ-Q/p/9899833.html