Why does the assignment operator return a value and not a reference?

后端 未结 4 1654
挽巷
挽巷 2021-02-04 12:04

I saw the example below explained on this site and thought both answers would be 20 and not the 10 that is returned. He wrote that both the comma and assignment returns a value,

4条回答
  •  情书的邮戳
    2021-02-04 12:16

    It doesn't have to do with values vs. references, it has to do with this values (as you suspected). In JavaScript, this is set entirely by how a function is called, not where it's defined. You set the this value in one of three ways:

    1. Call the function via an object property using property accessor notation, either dotted notation (obj.foo()) or bracketed notation (obj["foo"]()).
    2. Call the function via an object property using a with statement (really just a variant of #1, but worth calling out separately, particularly as it's not obvious from the source code)
    3. Use the apply or call features of the function instance.

    In your examples above, you're not doing any of those, so you end up calling the function with the default this value, the global object, and so x comes from there rather than from your foo object. Here's another way to think about what that code is doing:

    var f = foo.bar; // Not calling it, getting a reference to it
    f();             // Calls the function with `this` referencing the global object
    

    If you don't directly use a property to actually make the call (instead retrieving the value of the property and then making the call with that), the this handling doesn't kick in.

提交回复
热议问题