Search code examples
c++v8

What is the callbackfn argument of ArrayMap function in v8's source code?


In builtins-array-gen.cc

TF_BUILTIN(ArrayMap, ArrayBuiltinCodeStubAssembler) {
  Node* argc =
      ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount));
  CodeStubArguments args(this, argc);
  Node* context = Parameter(BuiltinDescriptor::kContext);
  Node* new_target = Parameter(BuiltinDescriptor::kNewTarget);
  Node* receiver = args.GetReceiver();

  Node* callbackfn = args.GetOptionalArgumentValue(0, UndefinedConstant());
  Node* this_arg = args.GetOptionalArgumentValue(1, UndefinedConstant());
  InitIteratingArrayBuiltinBody(context, receiver, callbackfn, this_arg,
                                new_target, argc);
  GenerateIteratingArrayBuiltinBody(
      "Array.prototype.map", &ArrayBuiltinCodeStubAssembler::MapResultGenerator,
      &ArrayBuiltinCodeStubAssembler::MapProcessor,
      &ArrayBuiltinCodeStubAssembler::NullPostLoopAction,
      Builtins::CallableFor(isolate(), Builtins::kArrayMapLoopContinuation));
}

I have no any Idea about what this callbackfn means.

Is this this_arg this pointer?

But in my mind, the first argument should be this pointer, so I am confused.

Thanks for your help.


Solution

  • Have a look at the documentation for Array.prototype.map: its signature is:

    arr.map(function callback(currentValue[, index[, array]]) {...} [, thisArg])
    

    And that's precisely what's reflected in the builtin you found, just expressed in V8's internal notation.

    receiver is the receiver of the call, i.e. the array that you call .map on, arr in the MDN example.

    callbackfn is the callback function, callback as MDN calls it.

    this_arg is the optional thisArg as MDN calls it.

    The fact that callbackfn is considered optional by that code doesn't reflect (and doesn't need to reflect) the specification; it's simply the most convenient way to safely handle the case where the user didn't pass a callback function. What matters is the resulting behavior, which is that a TypeError is thrown when callbackfn is not callable or missing (which is a special case of "not callable", because missing parameters are undefined, and undefined is not a function).