js输出结果题汇总

1.

	var 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.

	var obj = {"key":"1","value":"2"};
    var newObj = obj;
    newObj.value += obj.key;
    console.log(obj.value);

21

3.

	var 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. 闭包 - 函数作为返回值

	function create(){
        let b = 100;
        return function(){
            console.log(b);
        } 
    }
    let fn = create();
    let b = 200;
    fn();

100

5. 闭包 - 函数作为参数

	function 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)作为普通函数被调用:
function fn1(){
	console.log(this);
}
fn1();

window

(2)使用call调用:
function fn1(){
	console.log(this);
}
fn1.call({x: 100});

{x: 100}

(3)使用bind调用:
function fn1(){
	console.log(this);
}
const fn2 = fn1.bind({x:100});
fn2();

{x: 100}

(4)作为对象方法被调用:
const zhangsan = {
	name: '张三',
	sayHi(){
		// this即当前对象
		console.log(this);
	},
	wait(){
		setTimeout(function(){
			// this === window
			console.log(this);
		})
	}
}
(5)在class方法中调用:
class People{
	constructor(name){
		this.name = name;
		this.age = 20;
	}
	sayHi(){
		console.log(this);
	}
}
const zhangsan = new People('张三');
zhangsan.sayHi();

zhangsan对象

(6)箭头函数:

箭头函数中的this与它上级作用域的this相同。

const zhangsan = {
	name: '张三',
	sayHi(){
		// this即当前对象
		console.log(this);
	},
	wait(){
		setTimeout(() => {
			// this即当前对象
			console.log(this);
		})
	}
}

7. 作用域和自由变量

let i
for(i = 0; i <=3; i++){
	setTimeout(function(){
		console.log(i)
	}, 0)
}

4,4,4,4

for(let i = 0; i <=3; i++){
	setTimeout(function(){
		console.log(i)
	}, 0)
}

0,1,2,3

8. 作用域和自由变量

let a = 100
function test(){
	alert(a)
	a = 10
	alert(a)
}
test()
alert(a)

100
10
10

发布了23 篇原创文章 · 获赞 0 · 访问量 520

猜你喜欢

转载自blog.csdn.net/qq_33084055/article/details/103825362