简体   繁体   English

Object 属性以点表示法调用,显示 console.log 'undefined'

[英]Object property called with dot notation showing console.log 'undefined'

fairly new to Javascript. Javascript 相当新。

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as 'undefined' but when put in a function it works fine.我能否解释一下为什么 displayMyList 的 object 属性在使用点符号日志作为“未定义”访问时,但是当放入 function 时它工作正常。 Why does it show undefined with just the console log?为什么仅使用控制台日志显示未定义? Why doesn't it get displayed and why does it need a function to do so.为什么它不显示,为什么需要 function 来显示。

Here's the code.这是代码。

var toDoList = {
// Holding the List 
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}

This will display it as 'undefined' when I try to access the object property displayMyList with dot notation.当我尝试使用点符号访问 object 属性 displayMyList 时,这会将其显示为“未定义”。 However when a method is used it displays the list fine.但是,当使用一种方法时,它会很好地显示列表。 I am wondering why is that?我想知道为什么会这样?

 var toDoList = {
    // Holding the List 
    myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
    // Displaying the List
    displayMyList: function(){
  console.log(this.myList)
}
    }

First of all, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this首先,查看: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


var toDoList = {
  // Holding the List 
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: console.log(this.myList)
}

There are a couple problems here with your first example above.上面的第一个示例存在几个问题。

var toDoList = {
  // Holding the List 
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: function() {
    console.log(this.myList)
  }
};

This fixes those, you are:这解决了这些问题,您是:

  • Assigning displayMyList to be a FUNCTION that you will run later in the context of toDoList being this .将 displayMyList 指定为 FUNCTION ,稍后您将在toDoList的上下文中运行它this

Note how the use of function keyword here rebinds this to the containing object.请注意此处使用function关键字如何将this重新绑定到包含 object。

// Won't work
const x = toDoList.displayMyList;
x();

// Won't work
toDoList.displayMyList.call(globalThis);

// Won't work
toDoList.displayMyList.apply({});

You'll want to use an object method to log your list您需要使用object 方法来记录您的列表

 var toDoList = { // Holding the List myList: ['List1', 'List2', 'List3', 'List4', 'List5'], // Displaying the List displayMyList() { console.log(this.myList) }, } toDoList.displayMyList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM