How does 'this' work in JavaScript?

后端 未结 4 1465
长情又很酷
长情又很酷 2020-12-21 04:31

I know there are several other posts on this topic but they still leave me confused.

I\'ve included jQuery and everything and, I have a simple javascript class like

4条回答
  •  长情又很酷
    2020-12-21 05:10

    The confusing thing about this in javascript is it's relationship to the new operator. As you walk up the scope chain, this always refers to the last occruance of new. If need be, that means going all the way back to the window object. So if you have something like this:

    function MyObject() 
    { 
        this.baz = "some value"; 
        this.bar = function() { return this.baz; }
    }
    var foo = new MyObject();
    alert(foo.bar());
    

    it works as expected, because the foo variable was created with a new object/scope for the this keyword, and so the reference to this.baz points to the right place.

    But then if you do this:

    var foo = new MyObject();
    var bar = foo.bar;
    alert(bar());
    

    expecting to call foo's bar function, you're now calling it outside of the "scope" created for foo by the new operator. Your use of this inside the bar function now looks at the window object, which doesn't have a definition for baz.

    That may seem like an edge case, but it's important when working with frameworks like jQuery that create a lot of implicit objects using new or that expect you to pass functions around like variables. You have to be very careful.

提交回复
热议问题