面试题–this关键字

作者 : admin 本文共1744个字,预计阅读时间需要5分钟 发布时间: 2024-06-2 共4人阅读

this 指向是前端面试中的常问题型,简单分析为以下几种:

1. 在全局作用域中,this 关键字固定指向全局对象 window 或者 global。

2. 在函数作用域中,取决于函数是如何被调用的。

        1)函数直接调用,this 指向全局对象。

        2)通过一个对象的属性调用,格式为对象.属性()对象["属性"](),this指向该对象。

3. 使用构造函数创建对象时,构造函数中的 this 代表着 new 的对象。

4. 使用 call、apply、bind 绑定时,this 指向绑定的对象。

5. 箭头函数中 this 等于其定义环境中的 this,并且箭头函数一经创建,this 不能被任何方法改变。

对于 this 指向问题,不能仅仅了解理论知识,还需要实际应用,下面是一些常见的面试题。

面试题一:

console.log(this); 
function demo() {
  console.log(this);
}
demo(); 

let a = demo;
let array = [a, demo];
array[0]();
array[1](); 

let obj = {
  a,
  demo
};
obj.a();
obj.demo(); 

// 答案
// window 
// window
// 数组里,值调用,此时 this 指向数组,返回值是数组[],下面对象同理
// [ƒ, ƒ]
// [ƒ, ƒ]
// {a: ƒ, demo: ƒ}
// {a: ƒ, demo: ƒ}

结论一:this 在调用时才会知道指代的对象是谁,也就是说:谁调用函数,this 就指向谁,没有调用时候,this 指向未知。

面试题二:

const obj1 = {
  a: function () {
    console.log(this);
  },
  b: {
    x: 123,
    func: function () {
      console.log(this);
    }
  }
}
obj1.a();
obj1.b.func();
const temp = obj1.a;
temp();

// 答案
// {b: {…}, a: ƒ} 
// {x: 123, func: ƒ}
// window

结论二:如果将函数重新赋值一个新的变量,执行时指向 window,此时是函数直接被调用。

面试题三:

const obj = {
  firstName: 'sun',
  lastName: 'flower',
  age: 1,
  sayHello: function() {
    console.log(`My name is ${this.firstName}${this.lastName},and I am ${this.age} years old`);
  }
}
obj.sayHello(); 

const a = obj.sayHello;
a();

// 答案
// My name is sunflower,and I am 1 years old
// My name is undefinedundefined,and I am undefined years old
// 此时 a 里面只保存函数,而没有函数内部的值,因此均为 undefined。
let obj = {
  firstName: 'sun',
  lastName: 'flower',
  age: 1,
  sayHello: function() {
    console.log(`My name is ${obj.firstName}${obj.lastName},and I am ${obj.age} years old`);
  }
}
let b = obj;
obj = 123;
b.sayHello(); 

// 答案
// My name is undefinedundefined,and I am undefined years old

结论三:在对象内使用 this 最常见,this 指向当前被调用的对象,会实时改变,可以避免赋值导致的问题。

面试题四:

var obj = {
  fun1: function() {
    console.log(this);
    return function() {
      return this;
    };
  }
}
console.log(obj.fun1()());

// 答案
// obj对象本身:{fun1: ƒ}
// window

首先 obj.fun1() 调用后,返回 function(){ return this } 函数,该函数再次调用时与 obj 没有关系,所以返回 window。注意是二次调用,有两次输出,结果不同。

以上就是常见关于 this 指向的问题,有需要的小伙伴可以仔细研究一下,对面试很有帮助哦。

本站无任何商业行为
个人在线分享 » 面试题–this关键字
E-->