diff --git a/docs/javascript.md b/docs/javascript.md index e1b4b40..11053b5 100644 --- a/docs/javascript.md +++ b/docs/javascript.md @@ -42,6 +42,7 @@ function potentiallyBuggyCode() { let amount = 6; let price = 4.99; let home = 1e2; +let num = 1_000_000; // 位数过多可以用 _ 分割 let m = 0644; // 八进制数字 420 ``` @@ -142,13 +143,24 @@ abc.concat(" ", str2); // abc + " " + str2 abc.charAt(2); // 索引处的字符:“c” abc[2]; // 不安全,abc[2] = "C" 不起作用 // 索引处的字符代码:“c”-> 99 -abc.charCodeAt(2); +abc.charCodeAt(2); // 用逗号分割字符串给出一个数组 -abc.split(","); +abc.split(","); // 分割字符 -abc.split(""); +abc.split(""); +// 匹配开头字符串,如果忽略第二个参数,则从索引 0 开始匹配 +abc.startsWith("bc", 1); +// 匹配结尾的字符串,如果忽略第二个参数,则默认是原字符串长度 +abc.endsWith("wxy", abc.length - 1); +// padEnd 和 padStart 都用于填充长度,默认填充对象是空格 +"200".padEnd(5); // "200 " +"200".padEnd(5, "."); // "200.." +// 重复字符 +"abc".repeat(2); // "abcabc" +// trim、trimEnd 和 trimStart 用于去除首尾空格 +" ab c ".trim(); // "ab c" // 数字转为十六进制 (16)、八进制 (8) 或二进制 (2) -128.toString(16); +128.toString(16); ``` ### 数字 @@ -1178,6 +1190,100 @@ console.log(myCat.name); myCat.name = 'Yankee'; ``` +JavaScript this 绑定 +---- + +### 隐式绑定 + +```js +function foo() { + console.log(this) +} +let obj1 = { + name: "obj1", + foo: foo +} +let obj2 = { + name: "obj2", + obj1: obj1 +} +obj2.obj1.foo() // [Object obj1] +``` + +#### 隐式丢失 + +```js +let a = obj2.obj1.foo() +a() // Window +``` + +- 指定隐式绑定:必须在调用的对象内部有一个对函数的引用(比如一个属性) +- 将以上调用赋值给一个变量,结果最终会是 Window +- 在 a 被调用的位置没有进行过任何显示绑定,最终全局对象 window 会调用它(`Window.a`) + + +### 显示绑定 + +```js +function getName(a1, a2) { + console.log("此人" + this.name, "岁数" + (a1 + a2)) +} +let person = { + name: "zhangsan" +} +``` + +#### call + +call 第一个参数接受 this 作用域,剩余参数传递给其调用的函数 + +```js +getName.call(person, 18, 12) +``` + +#### apply + +apply 第一个参数与 call 相同,第二个参数是其调用函数的参数数组 + +```js +getName.apply(person, [18, 12]) +``` + +#### bind + +bind 函数会返回一个新函数 + +```js +getName.bind(person,18,12)() +//或者可以这样 +getName.bind(person)(18, 12) +//或者这样 +getName.bind(person).bind(null, 18)(12) +``` + +### 内置函数中的 this + +数组中的一些方法,类似于 map、forEach 等,可以自己设置绑定 this + +```js +const obj = { + name: "zhangsan" +} +const array = [1, 2, 3]; +array.map(function(value){ + console.log(this.name) +}, obj) +// zhangsan x3 +``` + +其中一些全局对象,如 setTimeout 等,它们和未显示绑定 this 的部分数组方法一样,都会指向全局对象(`Window`) + +```js +setTimeout(function(){ + console.log(this) +}, 1000) // Window +``` + JavaScript Classes ----