What's a valid left-hand-side expression in JavaScript grammar?

前端 未结 2 1100
挽巷
挽巷 2020-11-29 23:31

Okay, we all know what the valid left-hand-side expressions are. Kind of.*

But, looking at the definition from the ECMA-Script standard, I\'m very c

2条回答
  •  半阙折子戏
    2020-11-30 00:06

    To concisely answer your question, everything beneath the LeftHandSideExpression production is a valid LeftHandSideExpression.


    I think the question you are really asking is:

    What is a valid LeftHandSideExpression and also assignable?

    The answer to that is anything that resolves to a Reference which is a well defined concept in the specification. In your example

    new Object = 1;
    

    The new Object is a valid LeftHandSideExpression but it does not resolve to a Reference.

    (new Object).x = 1;
    

    The left hand side is a MemberExpression . IdentifierName which according to the spec the final step is:

    Return a value of type Reference ...


    If you consider it 2 separate properties it makes a lot more sense.

    1. Is it a valid LeftHandSideExpression?
    2. Is it a valid reference?

    Property 1 is determined in the syntactical analysis phase and property 2 is determined in the semantic analysis phase. Check out 8.7.2 PutValue (V, W) for more details.

    Here is a full explanation in the specification itself:

    8.7 The Reference Specification Type

    The Reference type is used to explain the behaviour of such operators as delete, typeof, and the assignment operators. For example, the left-hand operand of an assignment is expected to produce a reference. The behaviour of assignment could, instead, be explained entirely in terms of a case analysis on the syntactic form of the left-hand operand of an assignment operator, but for one difficulty: function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference. (Another reason not to use a syntactic case analysis is that it would be lengthy and awkward, affecting many parts of the specification.)


    After taking a look at your suggestion I believe it would throw off certain valid expressions (Note: I don't condone this.)

    function OuterObj() {
        this.Name = "Outer";
        this.InnerObj = function() {
            this.Name = "Inner";
        }
    }
    
    var obj; (obj = new new OuterObj().InnerObj).Name = "Assigned";
    

    This is a case where NewExpression is important

提交回复
热议问题