search

Home  >  Q&A  >  body text

javascript - When using object methods, why is there an extra undiffed in the console result?

Q1 Why did the console output two undiffed at the end?

var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: 'Hello'
  }
};

var hello = a.b.m;
hello()

Q2 feels like there is one more undiffed

//代码
var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: 'Hello'
  }
};
var hello = a.b;
hello.m();

Supplement:
Source of the problem:
This keyword in Ruan Yifeng’s JS standard
The above code is in the link, 2. (3) Object method The last paragraph

習慣沉默習慣沉默2825 days ago845

reply all(7)I'll reply

  • 漂亮男人

    漂亮男人2017-05-19 10:34:47

    Automatically answer, summarizing previous help:

    Q1
    The first one is undefined, because hello points to a method, which can be seen as functionName, so this is window
    this.p; //window.p//First declare a window.p, no value is assigned, the value is undiffed

    The key is that there is one more undiffed!
    The second undefined has an arrow in front of it.
    Add a return 'test' in the m function. //"test"
    So, this arrow can be regarded as the value after return. Here, the m function has no return. If there is no return value, it is undiffed
    Summary: The previous arrow is unique to the console. It is not available during command line debugging. The console first executes the function, and then outputs the execution result of the function (for example, it can be used to assign values ​​to other things)

    Q2

    The first one is undefined, because hello points to an object, which can be regarded as b, so

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:34:47

    is the return value of the last statement. Can you try adding a return "test" to the m function?

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:34:47

    Personally, I think the first undefined is because the function has no return value, and the second undefined may be due to browser debugging. Can you try using command line debugging to see if the second undefined appears.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:34:47

    Are you using the Chrome browser console? The second undefined is inherent and has nothing to do with your code.

    Enter var a = 1;

    There is also undefined when pressing Enter.

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:34:47

    I think it’s you. The this pointer of this method has changed the definition of the method in the a object to a variable under window. At this time, this points to window. There is no definition of p under window. You can declare one before var hello. var P will understand

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:34:47

    1.hello() has no return value
    2.console.log() This function has no return value

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:34:47

    Extra questionsundefined是js语句本身的值,剩下的就是this.

    reply
    0
  • Cancelreply