我无法将这段代码中的“ this”关键字引起来

时间:2019-07-07 15:50:50

标签: javascript

我正在使用JS中的promise并在记录“ this”时提出了奇怪的输出。“ this”的记录顺序影响了代码的输出。我以为我知道“ this”的工作原理,但显然我不知道可以,有人可以帮我绕下下面的代码吗?

const USER = {
    name: 'Glad Chinda',
    country: 'Nigeria',
    job: 'Fullstack Engineer'
  };

console.log(this);
Promise.resolve(USER).then(user => console.log(user.name));
console.log(this);

//OUTPUT
//{}
//{}
//Glad Chinda

------------------------------------------------------------------

//Removing the first console.log(this)
const USER = {
    name: 'Glad Chinda',
    country: 'Nigeria',
    job: 'Fullstack Engineer'
  };

Promise.resolve(USER).then(user => console.log(user.name));
console.log(this);

//OUTPUT
//{}
//Glad Chinda

------------------------------------------------------------------

//Removing the second console.log(this)
const USER = {
    name: 'Glad Chinda',
    country: 'Nigeria',
    job: 'Fullstack Engineer'
  };

console.log(this);
Promise.resolve(USER).then(user => console.log(user.name));

//OUTPUT
//{}
//Glad Chinda
------------------------------------------------------------------

//Removing both
const USER = {
    name: 'Glad Chinda',
    country: 'Nigeria',
    job: 'Fullstack Engineer'
  };

Promise.resolve(USER).then(user => console.log(user.name));

//OUTPUT
//Glad Chinda

2 个答案:

答案 0 :(得分:2)

“这”是您当前正在使用的范围。您的问题似乎是您对诺言的理解。 Promise异步执行,这意味着在Promise处理程序中的登录将在最后执行,因为它的执行被推迟了,以免阻塞程序的其余执行。

答案 1 :(得分:0)

Promise异步执行,这意味着行promise.resolve()之后的执行并行发生,而不是顺序发生。 您可以尝试这样做以获得清晰的了解:

Promise.resolve(USER).then(user => console.log(user.name));
Promise.resolve(USER).then(user => console.log(`${user.name} -> new entry`));

运行此代码,看看它能做什么。