javascript - When using object methods, why is there an extra undiffed in the console result?
習慣沉默
習慣沉默 2017-05-19 10:32:47
0
7
823

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

習慣沉默
習慣沉默

reply all(7)
漂亮男人

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

小葫芦

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

黄舟

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.

迷茫

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.

为情所困

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

黄舟

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

仅有的幸福

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template