this指向面试题两则

面试题1

let len = 10;
function fn() {
	console.info(this.len)
}
fn(); // A
let Person = {
	len: 5,
	say: function() {
		fn(); // B
		arguments[0](); // C
	}
}
Person.say(fn);

三处的输出结果均为 undefined

A 处执行结果

  • fnthis 指向为 window
  • let 声明的变量不挂载在 window 对象上
  • 输出结果为:window.len = undefined;

B处的执行结果

  • say 函数的 this 指向为 Person
  • fnthis 指向依然为 window
  • 输出结果依然为:window.len = undefined

C 处的执行结果

  • arguments[0]() 相当于 arguments.fn()
  • fnthis 指向为 arguments
  • 输出结果为:arguments.len = undefined

面试题2

var length = 10;
function fn() {
	console.info(this.length)
}
fn();  // A
let Person = {
	len: 5,
	say: function() {
		fn();  // B
		arguments[0]();  // C
	}
}
Person.say(fn);

分别输出 10, 10, 1

  • A , B 处直接输出 挂载到 window 对象下的 10
  • C 处输出 arguments.length = 1

猜你喜欢

转载自www.cnblogs.com/peaky/p/js-this.html