JavaScript经典习题

校园招聘前端笔试题:


1.请阅读以下代码,写出以下程序的执行结果。

var foo = '123';
	
function print() {
		
	var foo = '456';
		
	this.foo = '789';
		
	console.log(foo);
		
}
	
print();

答:输出456

解析:

这么简单还要解析,别学了回家种田吧。


由此扩展出一道题

...

请写出以下程序的执行结果。

var foo = '123';

function print() {
		
this.foo = '789';
	
console.log(foo);
	
}
	
print();

答:输出789

解析:

this.foo没被调用,在预编译的过程中所指向的是window。

所以函数体内的this.foo = '789'指向的是全局,预编译后函数体里的foo会覆盖var foo的值,所以输出的是789


2.以下程序运行test()new test()的结果分别是什么?

var a = 5;

function test() {
	
	a = 0;
	
	alert(a);
	
	alert(this.a);
	
	var a;
	
	alert(a);
	
}

答:

运行test()弹出0,5,0

运行new test()弹出0,undefined,0

解析:

运行test()这个就不说了,不会的话就回去种田。

运行new test()这个,容易把alert(this.a)误认为弹出0;函数体里没有this.a 这个值,所以只能弹出undefined。


3.请阅读以下代码,写出以下程序的执行结果。

function test() {
		
	console.log(a);
		
	var a = 1;
		
	console.log(a);
		
	console.log(hello)
}

tset();

答:

undefined,1,报错hello is not defined

解析:

这道题主要考的是预编译,其次JS语法错误。

前两次的话都会正常执行输出,执行到console.log(hello)的时候,因为没有hello这个变量,所以会报错,但是不影响之前的代码执行。


4.请阅读以下代码,写出以下程序的执行结果。

function demo() {
	
	var test;
	
	test();
	
	function test() {
		
	console.log(1);
		
	}
	
}

demo();

答案:

1

解析:

扫一眼就知道是1了,感觉这道题一把抓起我的智商按在地上摩擦。


5.请阅读以下代码,写出以下程序的执行结果。

var bar = {a : '002'};

function demo() {
	
bar.a = 'a';
	
Object.prototype.b = 'b';
	
return function inner() {
		
console.log(bar.a);
		
console.log(bar.b);
		
}
	
}

demo()();

答案:

a

b

解析:

唯一要说的就是demo()();把函数返回过来之后,再执行。

猜你喜欢

转载自blog.csdn.net/dfggffdd/article/details/80092717