首页 > 解决方案 > 全局上下文中的 Javascript this 不起作用,或者看起来像 console.log 工作但使用 ref 不起作用

问题描述

所以我想知道下面代码中两个调用之间的区别:我的理解是,一旦我使用 user.credential.getID 获得 ref 功能,我应该能够执行它并且在 console.log(user. credentials.getID());// 有效

const user = {
  id: 551,
  name: 'Tom',
  getID() {
    return this.id;
  },

  credentials: {
    id: 120,
    name: 'Jack',
    getID() {
      return this.id;
    }
  }

}
var getId = user.credentials.getId;
console.log(getId); // undefined why?
console.log(user.credentials.getID()); // it works

标签: javascriptthis

解决方案


只需记住一条规则,this即从调用函数的位置获取其值。如果你从一个对象调用一个函数,例如obj.func()this将是obj. 例如,如果您从任何地方调用它func()this将是undefinedwindow,这取决于您是否在strict mode


推荐阅读