Tuesday, December 27, 2022

Function.prototype.bind

Function.prototype.bind( boundThis, ...boundArgs )

Example

const person = {
    getFullName: function () {
        return this.firstName + " " + this.lastName;
    }
}

const thisPerson = {
	firstName   :   "John",
	lastName    :   "Xu",
}

let getFullName = person.getFullName.bind(thisPerson);

console.log( getFullName() )

Function.prototype.bind( boundThis, ...boundArgs )

  1. Let targetFunction be the this value. // for our example, person.getFullName
  2. If IsCallable(targetFunction) is false, throw a TypeError exception.
  3. Let boundArgs be a new List consisting of all of the argument values provided after boundThis(for our example, empty) .
  4. Let F be ?BoundFunctionCreate(targetFunction, boundThis, boundArgs)
            return {
                [[BoundTargetFunction]]: targetFunction,
                [[BoundThis]]: boundThis,
                [[BoundArguments]]: boundArgs,
                [[Prototype]]:targetFunction.[[Prototype]],
            }
        
  5. Perform SetFunctionName(F, name = Get(Target, "name"), prefix = "bound").

No comments:

Post a Comment