Java语言在全局上下文中不起作用,或者好像console.log有效,但使用ref不起作用

问题描述 投票:0回答:1

所以我想知道以下代码中两个调用之间的区别:我的理解是,一旦我获得使用user.credential.getID的功能的引用,我就应该能够执行它,并且它在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

所以,我想知道下面代码中的两个调用之间的区别:我的理解是,一旦我使用user.credential.getID引用函数,我应该能够执行它,并且似乎可以执行...]]

javascript this
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.