发布于 2026-01-06 0 阅读
0

JavaScript面试编程题 - 4

JavaScript面试编程题 - 4

继续回答问题……正如我在第一篇博客中所说,这些通常是基于评估的代码片段。

  1. 本文讨论的是箭头函数和常规函数定义的作用域差异。

    // 1. What will be logged? Why?
    const module1 = {
      x: 55,
      getX: function () {
        console.log('x:', this.x);
      }
    };
    
    const module2 = {
      x: 55,
      getX: () => {
        console.log('x:', this.x);
      }
    };
    
    (function() {
      this.x = 66;
      module1.getX();
      module2.getX();
    })();
    

    控制台输出如下:

    x: 55
    x: 66
    

    因为this在常规函数中,`$($($($($($($($($($($($($($($($($(($( ( this.x)x) module1...Windowglobal

    您可以在下方进行测试:

  2. 让我们用另一个例子来探讨同样的问题。

    // 2. What will be logged? Why?
    const message1 = {
      hello : 'Hello',
      names : ['Sue', 'Joe'],
      showMessage: function () {
        this.names.forEach(function(name) {
          console.log(`${this.hello} ${name}`);
        });
      }
    }
    message1.showMessage();
    
    const message2 = {
      hello : 'Hello',
      names : ['Sue', 'Joe'],
      showMessage: function () {
        this.names.forEach(name => {
          console.log(`${this.hello} ${name}`);
        });
      }
    }
    message2.showMessage();
    

    控制台输出如下:

    undefined Sue
    undefined Joe
    Hello Sue
    Hello Joe
    

    在`<script>` 标签内message1,内部函数this.names.forEach被定义为普通函数,因此this默认情况下等于全局对象(Window在浏览器中,global在 Node.js 中),并且它没有hello属性。在严格模式下,它this默认等于 ` undefined<script>` 标签!

    另一方面,在 `<function>` 中message2,内部函数this.names.forEach被定义为箭头函数。箭头函数没有自身的作用域,因此它的作用域等于所有者(showMessage在本例中为 `<function>`)的作用域。`<function>` 的作用域showMessage是包装对象message2。因此,我们可以通过 `<function>`访问hello`<function>` 的属性message2this.hello

    您可以在下方进行测试:

  3. 这个问题旨在考察你对 JavaScript 中 Promise 的理解程度。

    const promiser = ms => new Promise((resolve, reject) => {
      setTimeout(() => { resolve('wait wait..') }, ms)
    });
    
    const timeout = new Promise((resolve, reject) => {
      setTimeout(() => { resolve('timeout!') }, 2000)
    });
    
    const race1 = Promise.race([promiser(1000), timeout]);
    const race2 = Promise.race([promiser(3000), timeout]);
    
    // What will be the output?
    race1.then(res => console.log('race1:', res))
      .catch(err => console.log('race1:',  err));
    
    // What will be the output?
    race2.then(res => console.log('race2:', res))
      .catch(err => console.log('race2:', err));
    

    结果如下:

    race1: wait wait..
    race2: timeout!
    

    Promise.race()返回一个获胜的 Promise,它会先完成或拒绝。我们的timeoutPromise 会在 2 秒内完成。它将promiser完成时间作为参数。在第一轮比赛中,它在 1 秒内完成,因此赢得了比赛;但在第二轮比赛中,它需要 3 秒的时间完成,因此timeout更早完成。

    您可以在下方进行测试:

您可以通过以下链接阅读本系列之前的文章:



文章来源:https://dev.to/halilcanozcelik/javascript-interview-coding-questions-4-1fo7