Javascript this is undefined. This should be global object

前端 未结 2 523
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 04:43

Why do I get the following error in the google dev console when loading the script from a web page?

But if I step through the code with the dev tool debugger the err

相关标签:
2条回答
  • 2021-01-17 05:06

    Because you're kind of abusing the global namespace here, which is bad. this is usually assigned to window when there's no other scope. But if that function was handling, say a DOM event, then this would be the element that fired the event. So long story short, you should usually not rely on this to be set to something.

    Either set it explicitly using call or apply, as very nicely explained here: What is the difference between call and apply?.

    Or save a particular this and define your function as a closure around it:

    self = window;
    self.name = 'Jane Doe';
    self.greet = function () {
        return 'My name is ' + self.name;
    };
    console.log(self.greet());
    

    That code makes me feel dirty though. Only clobber the global namespace like that if you Absolutely must. Like, for example, when you're defining the jQuery variable, or the ko variable (with knockout). And even then, don't do it like this :)

    Of course this is totally fine to use, but you should really understand it properly before using it. And that goes beyond the scope of this question.

    0 讨论(0)
  • 2021-01-17 05:09

    this is not bound to the global object in strict mode.

    The value of this is not converted to the global object when it is null or undefined. JavaScript

    function testFunc() {
        return this;
    }
    var testvar = testFunc();
    

    In non-strict mode, the value of testvar is the global object, but in strict mode the value is undefined.

    http://msdn.microsoft.com/en-us/library/br230269(v=vs.94).aspx

    That solves most of it. I still can't explain why it works while stepping through the code in the chrome debugger.

    0 讨论(0)
提交回复
热议问题