Function.prototype.call()

Methods to introduce

grammar

function.call(thisArg, arg1, arg2, ...)
Copy the code

parameter

thisArg

Optional. The this value used when function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped.

arg1, arg2, ...

Specifies the argument list.

The return value

Call the return value of the function with the this value and arguments provided by the caller. If the method returns no value, undefined is returned.

describe

Call () allows different objects to assign and call functions/methods belonging to one object.

Call () provides the new this value for the currently called function/method. You can use Call to implement inheritance: write a method and then have a new object inherit it (instead of writing the method again in the new object).

Handwritten summary of ideas

  • If the first argument received is null or undefined, this is automatically specified as window
  • Call immediately executes the function and returns the result of the function execution after changing the this pointer inside the function
  • The function executed is the one that calls the current call method, which can be interpreted as the default this inside the call method
  • After execution, the assigned context object is cleared

Handwritten Call method

/ / method is mounted on the Functin of prototype, so all functions you can call the Function. The prototype. MyCall = Function (context,... (arr) {if the context = = = null | | context = = = undefined) {/ / if the incoming this object to null, and undefined, Context = window} else {// Prevent this from specifying the original value, Context = Object(context) // The value is the original value (number, string, } const specialPrototype = Symbol('only') const specialPrototype = Symbol('only') // Defines a unique attribute to hold the function that will be executed next // The current this is the function called // equivalent to context.specialPrototype = the function to be executed. So the function that needs to be executed is called by the context, which means, Context Context [specialPrototype] = this // This points to the function implicitly bound to the context. let result = context[specialPrototype](... Arr) // Execute function by implicit binding and pass argument delete Context [specialPrototype] // delete properties of context object return result // Return function execution result}Copy the code

Function.prototype.apply()

Methods to introduce

grammar

func.apply(thisArg, [argsArray])
Copy the code

parameter

thisArg

Will be selected. The this value used when the func function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped.

argsArray

Optional. An array or array-like object whose array elements are passed as individual arguments to the func function. If the value of this parameter is null or undefined, no arguments need to be passed in. Array-like objects can be used starting with ECMAScript 5. See the bottom of this article for browser compatibility. Return value The result of calling the function with the specified this value and argument.

describe

When calling an existing function, you can specify a this object for it. This refers to the current object, the object on which the function is being called. With Apply, you can write the method once and then inherit it from another object instead of repeating the method in a new object.

Apply is very similar to Call (), except for the way arguments are provided. Apply uses an array of parameters rather than a list of parameters. Apply can use array literals, such as fun.apply(this, [‘eat’, ‘bananas’]), or array objects, Fun. apply(this, new Array(‘eat’, ‘bananas’)).

You can also use the Arguments object as the argsArray argument. Arguments is a local variable to a function. It can be used as any unspecified arguments to the called object. This way, you don’t need to know all the parameters of the called object when using Apply. You can use arguments to pass all arguments to the called object. The called object is then responsible for handling these parameters

Handwritten summary of ideas

  • The idea is similar to the call method, except that the parameters of apply become arrays
  • An extra check on the array is whether it is a composite array of requirements

Handwritten Apply method

/ / method is mounted on the Functin of prototype, so all functions you can call the Function. The prototype. MyApply = Function (context) {/ / if the incoming this object to null, and undefined, Will function within this automatic pointing in the global object (in the browser window) as if (context = = = null | | the content = = = undefined) = {context window} else {/ / // Avoid specifying a raw value, Context = Object(context)} function isArrayLike(o) {if (o && // Typeof o === 'object' && // o is the object isFinite(O.length) && // O.Length is the finite value o.Length >= 0 && // O.length === math.floor (O.length) && // O.length is an integer o.length < math.pow (2, 32) // o.length < 2^32 ) return true else return false } const specialPrototype = Symbol('only') // Context [specialPrototype] = this // implicitly bind this to context let args = arguments[1] // Get array let Result if (args) {// If (! Array.isArray(args) && ! IsArrayLike (args)) {throw new TypeError(' parameter TypeError ')} else {args = array. from(args) // convert to Array result = context[specialPrototype](... // Execute the function and expand the array, Pass function arguments}} else {result = context[specialPrototype]() // execute function} delete Context [specialPrototype] // remove the property of the context object return Result // Return function execution result}Copy the code

Function.prototype.bind()

Methods to introduce

grammar

function.bind(thisArg[, arg1[, arg2[, ...]]])
Copy the code

parameter

thisArg

The value passed to the target function as the this parameter when the binding function is called. If the new operator is used to construct the binding function, this value is ignored. When using bind to create a function in setTimeout (provided as a callback), any raw values passed as thisArg are converted to Object. If bind’s argument list is empty, or thisArg is null or undefined, this executing the scope will be treated as thisArg for the new function.

arg1, arg2, ...

Arguments that are preset into the argument list of the binding function when the target function is called.

The return value

Returns a copy of the original function with the specified this value and initial arguments.

describe

Bind () creates a new bound function (BF). The binding function is an Exotic Function object (exotic function object, ECMAScript 2015 terminology) that wraps the original function object. Calling a binding function usually results in the execution of a wrapper function. Binding functions have the following internal properties:

  • [BoundTargetFunction] – The wrapped function object
  • [BoundThis] – The value that is always passed as this value when the wrapper function is called.
  • [BoundArguments] – lists, which are populated with list elements in preference to any calls to wrappers.
  • [Call] – Executes the code associated with this object. Called by a function call expression. The arguments to the inner method are a this value and a list of arguments passed to the function by calling the expression.

When the binding function is called, it calls the internal method Call on BoundTargetFunction, like Call(boundThis, args). Where boundThis is boundThis and args is BoundArguments plus the list of arguments passed in through the function call.

Binding functions can also be constructed using the new operator, which behaves as if the target function has already been constructed. The supplied this value is ignored, but the leading argument is still supplied to the simulation function.

Handwritten summary of ideas

The following features of the BIND method are summarized:

  • After calling bind, returns a function with an internal this change. The function is not executed immediately;
  • The first of the received arguments is the executed this object, followed by optional arguments that specify the default arguments of the return function.
  • The returned function may continue to pass parameters when it is called, that is, a second pass
  • If the returned method is constructed as new, the supplied this argument is ignored. This refers to the instance object of the current function

Write a bind

Function.prototype.myBind = function (newThis, ... Params) {const oldFn = this // saves the original function // defines the function that the bind side finally returns, which can take the argument let newFn = function (... SecondParams) {// First check whether newFn is constructed by new, Const isNew = this instanceof newFn const Context = isNew? this : Object(newThis) // If called by new, this pointer stays the same, otherwise this pointer is modified to bind the method to the newThis passed in. // According to MDN, internal implementation can use call to modify this and execute the function. Return oldFn. Call (context,... params, ... } if (oldFn. Prototype) {// copy the function's prototype to newFn. NewFn. Prototype = oldFn. Prototype} return newFn // return the copied function}Copy the code

test

let user = { name: 'Jason', age: 23, } function Fun(school) { this.school = school; console.log(this.name); console.log(this.age); console.log(this.school); } let fun = fun. myBind(user, 'jianyu '); // this -> user fun() let obj = new fun(); console.log(obj.__proto__ === Fun.prototype) // tureCopy the code