0

I think the console should return 34 for me,but I got "undefined" in the vscode ide.

enter image description here

I run below code in the chrome, then I got 34.

enter image description here

I want to know why,and if my settings is the reason, how should I modify the settings?

   function foo() {
        console.log( this.a );
    }

    var obj = {
        a: 2,
        foo: foo
    };

    var bar = obj.foo;

    var a = 34;

    bar();

Thanks

Shawn Li
  • 53
  • 1
  • 11
  • 1
    Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andy Ray May 01 '17 at 06:23
  • I know the mechanism of "this", I just try to write a simple example in the vscode.I also know the result.But I don't got that in the vscode, so I just ask this question,It's about vscode not js. – Shawn Li May 01 '17 at 06:26
  • Yes, I put function foo to the property of foo, and I put the obj.foo to the variable “bar”, and I called "bar" in the snippet last line. – Shawn Li May 01 '17 at 06:59

2 Answers2

3

As I have tested and as below pictures can show

this in Chrome Debugger referred to window but in VSCode it be an object which have some Symbol (for example variables names)

so the main reason is the difference behavior between VSCode debugger and Chrome.

In VSCode: enter image description here

In Chrome:enter image description here

Aria
  • 3,724
  • 1
  • 20
  • 51
0

The reason why the output is 34 lies in what exactly bar is

And actually it's because bar points to the global function foo

Finally, when you call bar(), you don't actually call obj.foo(), but the global foo. And in JavaScript, the this value is only defined when you call the function and this is the context where you are calling the function, which is in this case, the window, and window.a points to 34.

There's nothing wrong with your settings.

Feel free to read this awesome article and leave your comment below! How does the "this" keyword work?

Community
  • 1
  • 1
Chang
  • 1,658
  • 1
  • 17
  • 23
  • So can you explain me that why above snippet in the vscode print "undefined"? – Shawn Li May 01 '17 at 06:59
  • 1
    @ShawnLi The `undefined` is the return value of your global function `foo`, since it returns nothing. – Chang May 01 '17 at 07:03
  • Thanks, I regarded the undefine as the result of the function print.But I can't find the right result in the vscode.It's so strange. – Shawn Li May 01 '17 at 07:08
  • Sorry, I just changed my code, when I delete the "this" keyword, console show "34", it's not return value – Shawn Li May 01 '17 at 07:17