前言
类比法是一种学习方法,它是通过将新知识与已知知识进行比较,从而加深对新知识的理解。在学习 JS
语言的过程中,我发现,通过类比已有的前端知识,可以更好地理解 JS
语言的特性。
语法对比
import 包方式
JS
语言的包导入方式与后端的模块导入方式类似,都是通过 import
关键字导入,但是 Go
语言的导入方式更加简洁,只需要写包名即可,不需要写路径。
1 2 3 4 5 6 7 8 9
| // go import ( "a" "b" )
// js import a from "a"; import b from "b"
|
变量声明
1 2 3 4 5 6 7 8
| // go var x string = "x"; x := "x" // 自动把变量类型、声明和赋值都搞定了
// js var a = "a"; let b = "b"; const c = "c";
|
条件
1 2 3 4 5 6 7 8 9 10 11 12 13
| // go if a == "go" {
} else {
}
// js if (a === "js") {
} else {
}
|
循环
1 2 3 4 5 6 7 8 9
| // go for i := 0; i < 100; i++ {
}
// js for(let i = 0; i < 100; i++) {
}
|
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| // go func helloGo() { fmt.Println("hello go"); }
func learnGo() { fmt.Println("learn go");
learnGo(); }
// js function helloJS() { console.log("hello js");
learnJS(); }
function learnJS() { console.log("learn js"); }
|
在语法层面的相似之处,加深了我对 JS
的理解,让我更容易上手 JS
。
以上。