返回
探秘JavaScript的this指向问题:面试中如何应对?
前端
2024-01-30 10:18:39
this指向的本质
this指的是函数运行时所在的环境(即调用的对象)。对于函数的保存:实际函数属性的值是函数的地址;(而函数本身,可理解为:它不属于任何一个对象,相当于一个全局对象。所以,函数在不同场景下运行,this就是不同的场景了,不过都是执行时的环境) 同时,函数,可以作为一个参数(值)…。
面试例题
- 在以下代码中,this指向什么?
function Person(name) {
this.name = name;
}
const person1 = new Person('John');
console.log(person1.name); // 'John'
const person2 = Person('Mary');
console.log(person2.name); // undefined
- 在以下代码中,this指向什么?
const obj = {
name: 'John',
sayName: function() {
console.log(this.name);
}
};
obj.sayName(); // 'John'
const sayName = obj.sayName;
sayName(); // undefined
- 在以下代码中,this指向什么?
function Person(name) {
this.name = name;
const sayName = function() {
console.log(this.name);
};
return sayName;
}
const person1 = new Person('John');
const sayName1 = person1.sayName;
sayName1(); // 'John'
const person2 = new Person('Mary');
const sayName2 = person2.sayName;
sayName2(); // 'Mary'
答案
-
person1,因为this指向函数运行时所在的环境,在构造函数中,this指向新创建的对象person1。person2没有使用new调用Person函数,所以this指向全局对象(window)。
-
undefined,因为sayName函数被赋给变量sayName后,失去了与obj的关联,因此this指向全局对象(window)。
-
person1和person2,因为sayName函数作为Person函数的返回值,被person1和person2分别调用。因此,this指向调用sayName函数的对象,即person1和person2。
结语
this指向问题是JavaScript面试中的常见话题,掌握this指向的原理和常见用法,可以帮助您在面试中展现出扎实的基础知识和对JavaScript语言的深刻理解。