1、js预编译
步骤:
- 1、创建AO对象(AO:{})
- 2、找到形参和对象的声明(abc),作为对象的属性名,值为undifined
- 3、实参和形参相统一(a=1,b=2)
- 4、找到函数声明,会覆盖变量的声明(a=function a() { },b=function b() { })
习题:
<script> function test(a, b) { console.log(a) // function a() { } var a = 123 console.log(a) // 123 console.log(b) // function b() { } function a() { } if (false) { var c = 123 } // 为假,不执行 console.log(c) // undefined var c = function () { } console.log(c) // function () { } var b = 123 console.log(b) // 123 function b() { } } test(1, 2) // - 预编译 // - 1、创建AO对象 // - 2、找到形参和对象的声明,作为对象的属性名,值为undifined AO: { a: undefined b: undefined c: undefined } // - 3、实参和形参相统一 AO: { a: undefined, 1 b: undefined, 2 c: undefined } // - 4、找到函数声明,会覆盖变量的声明,(var c = function () { }是定义,不是声明) AO: { a: undefined, 1, function a() { } b: undefined, 2, function b() { } c: undefined } </script>
2、js-this
- 1、函数被直接调用:fun.call(window)
- 2、函数作为对象被调用:fun.run.call(fun)
习题:
<script> // 1、在函数中直接使用 function get(content) { console.log(content) } get('hello,world') // 1、相当于 get.call(window, 'hello,world') // 2、函数作为对象被调用 var person = { name: 'jasmine', run: function (time) { console.log(`${this.name},${time}`) } } person.run(30) // 2、相当于 person.run.call(person,30) var name = 222 var a = { name: 111, say: function () { console.log(this.name) } } var fun = a.say fun() // 1、相当于 fun.call(window),结果为:222 a.say() // 2、相当于 a.say.call(a),结果为:111 var b = { name: 333, say: function (fun) { fun() } } b.say(a.say) // 1、fun() 相当于 fun.call(window),结果为:222 b.say = a.say b.say() // 2、相当于 b.say.call(b),结果为:333 </script>
3、js箭头函数的this
- 简言之,一句话:箭头函数的this就是外层代码块的this,箭头函数不能当作构造函数
<script> // 简言之,一句话:箭头函数的this就是外层代码块的this,箭头函数不能当作构造函数 var a = 111 var test = { a: 222, say: () => { console.log(this.a) } } test.say() // say()函数跟test对象平级,所以调用a=111,结果为:111 var test = { a: 333, say: function () { console.log(this.a) } } test.say() // say()函数写在function里面,say()函数比test对象低一级,所以调用a=333,结果为:333 </script>