1.
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19var a = 1; function Fn1(){ var a = 2; console.log(this.a + a); } function Fn2(){ var a = 10; Fn1(); } Fn2(); var Fn3 = function(){ this.a = 3; } Fn3.prototype = { a:4 } var fn3 = new Fn3(); Fn1.call(fn3);
3
5
2.
复制代码
1
2
3
4
5var obj = {"key":"1","value":"2"}; var newObj = obj; newObj.value += obj.key; console.log(obj.value);
21
3.
复制代码
1
2
3
4
5
6
7
8
9
10
11var m = 1, j=k=0; function add(n){ return n = n+1; } y = add(m); function add(n){ return n = n + 3; } z=add(m); console.log(y + ',' + z);
4,4
4. 闭包 - 函数作为返回值
复制代码
1
2
3
4
5
6
7
8
9
10function create(){ let b = 100; return function(){ console.log(b); } } let fn = create(); let b = 200; fn();
100
5. 闭包 - 函数作为参数
复制代码
1
2
3
4
5
6
7
8
9
10function print(fn1){ let d = 200; fn1(); } let d = 100; function fn1(){ console.log(d); } print(fn1);
100
注:自由变量的查找,是在函数定义的地方,向上级作用域中查找。不是在执行的地方!
6. this
this使用场景:
- 作为普通函数被调用
- 使用call、apply、bind调用
- 作为对象方法被调用
- 在class方法中调用
- 箭头函数
⚠️this在各个场景中取什么值是在函数执行的时候确定的,不是在函数定义的时候确定的!
(1)作为普通函数被调用:
复制代码
1
2
3
4
5function fn1(){ console.log(this); } fn1();
window
(2)使用call调用:
复制代码
1
2
3
4
5function fn1(){ console.log(this); } fn1.call({x: 100});
{x: 100}
(3)使用bind调用:
复制代码
1
2
3
4
5
6function fn1(){ console.log(this); } const fn2 = fn1.bind({x:100}); fn2();
{x: 100}
(4)作为对象方法被调用:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14const zhangsan = { name: '张三', sayHi(){ // this即当前对象 console.log(this); }, wait(){ setTimeout(function(){ // this === window console.log(this); }) } }
(5)在class方法中调用:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12class People{ constructor(name){ this.name = name; this.age = 20; } sayHi(){ console.log(this); } } const zhangsan = new People('张三'); zhangsan.sayHi();
zhangsan对象
(6)箭头函数:
箭头函数中的this与它上级作用域的this相同。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14const zhangsan = { name: '张三', sayHi(){ // this即当前对象 console.log(this); }, wait(){ setTimeout(() => { // this即当前对象 console.log(this); }) } }
7. 作用域和自由变量
复制代码
1
2
3
4
5
6
7let i for(i = 0; i <=3; i++){ setTimeout(function(){ console.log(i) }, 0) }
4,4,4,4
复制代码
1
2
3
4
5
6for(let i = 0; i <=3; i++){ setTimeout(function(){ console.log(i) }, 0) }
0,1,2,3
8. 作用域和自由变量
复制代码
1
2
3
4
5
6
7
8
9let a = 100 function test(){ alert(a) a = 10 alert(a) } test() alert(a)
100
10
10
最后
以上就是鲜艳大炮最近收集整理的关于js输出结果题汇总的全部内容,更多相关js输出结果题汇总内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复