调用时机
1.
let i = 0for(i = 0; i<6; i++){setTimeout(()=>{console.log(i)},0)}
打印 6个6
因为setTimeout回调会在代码执行完后在执行,此时i已经增长为6
2.
for(let i = 0; i<6; i++){setTimeout(()=>{console.log(i)},0)}
打印0、1、2、3、4、5
因此每次再for循环的时候,内部悄悄地给复制出了一个i,有点奇葩
3.
while(i<6){console.log(i)i++ }
所有函数都是由Function构造出来的
任何函数.proto === Function.prototype
如何传 arguments
调用 fn 即可传 arguments
fn(1,2,3) 那么 arguments 就是 [1,2,3] 伪数组
如何传 this
目前可以用 fn.call(xxx, 1,2,3) 传 this 和 arguments
而且 xxx 会被自动转化成对象(JS 的糟粕)
用use strict可以处理
箭头函数
箭头函数没有this arguments
let f1 = x => x*x
let f2 = (x,y) => x+y // 圆括号不能省
let f3 = (x,y) => {return x+y} // 花括号不能省
let f4 = (x,y) => ({name:x, age: y}) 直接返回对象会出错,需要加个圆括号(头疼)
代码
function fn(){console.log(arguments)console.log(this)}
Call
const animals = [{species: 'Lion', name: 'King'},{species: 'Whale', name: 'Fail'}]for(let i=0;i<animals.length;i++){(function(i){this.print = function(){console.log("species: " + this.species + " name:" + this.name)}this.print()}).call(animals[i], i)}
一个重要的函数写法
ajax('GET', '/xxx', {success(response){},fail: (request, status)->{}})//success 是function的缩写//fail 是箭头函数
重要:方方老师教程看懂this
https://zhuanlan.zhihu.com/p/23804247
把所有函数调用都在脑海中转化为function.call()
