views:

49

answers:

1

Hi,

I am reading ECMAScript Language Specification Function Calls section

Can someone rephrase or detailed explains the following sentense for me?

The production CallExpression : MemberExpression Arguments is evaluated as follows:

  1. Evaluate MemberExpression.

let's take this code as an example.

var john = { 
  name: 'John', 
  greet: function(person) { 
    alert("Hi " + person + ", my name is " + this.name); 
  } 
}; 

john.greet("Mark");

Take above code as an example, what does production CallExpression mean? what is MemberExpression in this case, john.greet?

Thanks!

+2  A: 

The MemberExpression is john.greet. Basically what it's saying is: Step 1: Figure out what function to call. :-) The john part is important, because it comes into it later.

Here's the complete quote from the most recent specification (your link is to the 3rd edition, which has been superceded by the 5th edition; this didn't change much though):

  1. Let ref be the result of evaluating MemberExpression.
  2. Let func be GetValue(ref).
  3. Let argList be the result of evaluating Arguments, producing an internal list of argument values (see 11.2.4).
  4. If Type(func) is not Object, throw a TypeError exception.
  5. If IsCallable(func) is false, throw a TypeError exception.
  6. If Type(ref) is Reference, then
      a. If IsPropertyReference(ref) is true, then
        i. Let thisValue be GetBase(ref).
      b. Else, the base of ref is an Environment Record
        i. Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).
  7. Else, Type(ref) is not Reference.
      a. Let thisValue be undefined.
  8. Return the result of calling the [[Call]] internal method on func, providing thisValue as the this value and providing the list argList as the argument values.

As you can see, john comes into it again at 6(a) because the expression is a property reference, so the this value is john (rather than the global object, as it would be if you called this not through a property reference).

If you're reading the spec, I do recommend reading the newest one instead of the older one (no HTML version yet). I'm afraid the prose is no less turgid, though. :-)

T.J. Crowder
Indeed, trying to actually read the ECMA262 spec is not good for your health. Even for language lawyers this is beastly stuff. The trick in this case is that “evaluate” doesn't entirely mean what a normal programmer might imagine; the result is not a simple value but something that still holds a reference to the MemberExpression `john`, allowing the `this` magic to work.
bobince
@bobince: Yeah. :-) The good news is that, as I understand it, now that 5th edition is out the team wants to change how they spec this stuff going forward to be more accessible. To which I say: What, and ruin all our fun?
T.J. Crowder
thanks! it is not fun at all, it is like reading a legal document :(
Ding
@Ding: Yeah, but without the laughs. ;-)
T.J. Crowder