随着越来越深入JavaScript,现在所考察和学习到的code已经不是肉眼扫过去就能理解,而且包含着JavaScript这语言本身的特点,因此针对这些较难理解和混淆的部分来作笔记:var、let和const的差异,forEach和map的功能箭头函式,以及new的概念。
大家可以参考这篇,简单的说就是var会污染到全域变数(如果在函式外也有宣告),let只在区块作用域内,也就是 { },const作用区域与let相同,且宣告时需给值,且重新赋值(有例外)。其中所谓var会污染到全域变数可以参考下面两个例子:
var x = 0;
function f(){
var x = y = 1; // x is declared locally. y is not!
}
f();
console.log(x, y); // Throws a ReferenceError in strict mode (y is not defined). 0, 1 otherwise.
// In non-strict mode:
// x is the global one as expected
// y leaked outside of the function, though!
var x = 0; // x is declared global, then assigned a value of 0
console.log(typeof z); // undefined, since z doesn't exist yet
function a() { // when a is called,
var y = 2; // y is declared local to function a, then assigned a value of 2
console.log(x, y); // 0 2
function b() { // when b is called
x = 3; // assigns 3 to existing global x, doesn't create a new global var
y = 4; // assigns 4 to existing outer y, doesn't create a new global var
z = 5; // creates a new global variable z and assigns a value of 5.
} // (Throws a ReferenceError in strict mode.)
b(); // calling b creates z as a global variable
console.log(x, y, z); // 3 4 5
}
a(); // calling a also calls b
console.log(x, z); // 3 5
console.log(typeof y); // undefined as y is local to function a
forEach和map都是array的功能,这边可以参考这篇,而先看下面这张map的介绍图(原文):
array可以最多将3个参数丢到後面(後两个是option),而map和forEach的差异在map是回传值,而forEach是直接作用在该array上。
该篇里面还介绍array的其他功能像filter、find、every,some等,而这些功能的架构与map相同,都是可以丢value、index和array进去,差异是在回传的功能如同它的名称,另外比较特别的是reduce,它丢进去的依序可以是前一个回传值、目前值、当前索引值、和阵列。
=>此符号即所谓箭头函式,可以参考这篇说明,屏除一些花式的写法(例如搭配this),简单说就是会回传值的function简洁表示法(有点像Python的lambda),可以将前方的参数丢入後方使用,常搭配像在前段的map中使用。
new不new主要有两个差异,new了会呼叫constructor,new了才有this(不然this为window),参考文章中的太复杂,我们可以看以下例子:
function friend(name) {
this.name = name;
console.log("what is this? ", this);
}
const friend1 = new friend("Leonard");
//[object Object]
const friend2 = friend("Leonard");
//[object Window]
console.log(friend1.name);
// expected output: "Leonard"
console.log(friend2.name);
// Error: Cannot read properties of undefined (reading 'name')
>>: 部署 Google App Script 专案(1)
在[Day 16]和[Day 17]「TFLM + BLE Sense + MP34DT05 就成了...
接下来我会看看相关网页是如何设计的,这里参考了约 10 个国家的气象局官网,但囿於内容篇幅,仅简单列...
一、前言 Linux 上面多半有 Firefox,为什麽我还大费周章安装 Google Chrome...
前言 如果两个 transaction 没有接触到相同的资料,则它们可以很愉快的 并发 (concu...
(我想到的这个标题真的很误导人。因为「不是只有爱用iPhone的设计师会有这些毛病。」) 下面这是在...