Node.js是一个基于谷歌的 chrome V8 引擎的 JavaScript 运行时环境
Node.js 版本至少是 v14.8.0,最新版本的 Node 能够理解 JavaScript 最新版本的特性,因此代码不需要被转译。
代码文件以 .js结尾,通过node 文件名.js命令以运行文件。
你也可以选择 JS Bin这样的工具。
本课程中明确不建议使用var,你应该坚持使用 const 和 let!
在本课程中,我们将使用箭头语法定义所有函数。
箭头函数
箭头函数如果只有一个表达式,去掉花括号,则返回表达式的值
const fn = (a,b) => a + b
如果不是表达式,而是函数调用,也可以去掉花括号
如果函数调用没有返回值,则只是执行调用函数
如果函数调用有返回值a,则箭头函数的返回值也等于a
const f1 = (a,b) => a + bconst f2 = () => f1(1,2)let a = f2() // 3
const f1 = (a,b) => a + bconst f2 = () => {f1(1,2)}let a = f2() // undefined
const f1 = (a) => console.log(a)// 等价于 const f1 = (a) => { console.log(a) }f1('hello')
Array
forEach
const t = [1, -1, 3]t.push(5)t.forEach(value => {console.log(value) // numbers 1, -1, 3, 5 are printed, each to own line})
concat
不会向旧数组添加新的元素,而是直接返回一个新数组
const t = [1, -1, 3]const t2 = t.concat(5)console.log(t) // [1, -1, 3] is printedconsole.log(t2) // [1, -1, 3, 5] is printed
map
基于旧的数组,map 创建一个 新的数组,旧数组的每一项作为函数的入参来创建新的元素。
map 在 React 中使用得相当频繁。
const t = [1, 2, 3]const m1 = t.map(value => value * 2)console.log(m1) // [2, 4, 6] is printed// Map 还可以将数组转换为完全不同的内容:const m2 = t.map(value => '<li>' + value + '</li>')console.log(m2)// [ '<li>1</li>', '<li>2</li>', '<li>3</li>' ] is printed
解构赋值
const t = [1, 2, 3, 4, 5]const [first, second, ...rest] = tconsole.log(first, second) // 1, 2 is printedconsole.log(rest) // [3, 4 ,5] is printed
exercise 1.3 -1.5
专业提示: 当涉及到组件接收的props 的结构时,您可能会遇到问题。 一个很好的方法就是把props打印到控制台上,例如:
const Header = (props) => {console.log(props)return <h1>{props.course}</h1>}
由于在本课程中我们使用的React版本里包含 React hook ,所以我们不需要定义带有函数的对象。
this
const arto = {name: 'Arto Hellas',age: 35,education: 'PhD',greet: function() {console.log('hello, my name is ' + this.name)},doAddition: function(a, b) {console.log(a + b)},}arto.greet() // "hello, my name is Arto Hellas" gets printedconst referenceToGreet = arto.greetreferenceToGreet() // prints "hello, my name is undefined"
在 JavaScript 中,this的值是根据 方法如何调用 来定义的。 当通过引用调用该方法时, this 的值就变成了所谓的全局对象;
当 setTimeout 调用该方法时,实际上是JavaScript引擎在调用该方法,此时的this是指向的是全局对象。
setTimeout(arto.greet, 1000)
有几种机制可以保留这种原始的 this 。 其中一个是使用bind方法:
setTimeout(arto.greet.bind(arto), 1000)
