Apply, call, and bind are mounted onFunctionObject, which must be called as a function.Copy the code
  • In the browser, this in global scope points to the window
  • Inside a function, this always refers to the object that last called it
  • In the constructor, this refers to the object coming out of new
  • This in call, apply, and bind is forced to be bound to the object it points to
  • The arrow function is special in that it refers to this in its parent scope

Implement a bind function

Function.prototype.myBind = function (context) {
     // No function throws an exception
    if (typeof this! = ='function') {
        throw new Error('Type error')}let _this = this
    // Retain the value passed by the previous function
    let args = Array.prototype.slice.call(arguments.1)
    return function () {
        Args. Concat (arguments) These two sequences cannot change arguments to an array of classes without concat methods
        _this.apply(context, args.concat(arguments))}}Copy the code

Implement an apply function

This always refers to the object that called it last
Function.prototype.myApply = function (context) {
    if (typeof this! = ='function') {
        throw new Error('Type error')}let key = Symbol('key')
    context[key] = this
    let result = context[key](Array.prototype.slice.call(arguments.1))
    delete context[key]
    return result
}
Copy the code

Implement a call function

Function.prototype.myCall = function (context, ... ags) {
    if (typeof this! = ='function') {
        throw new Error('Type error')}let key = Symbol('key')
    context[key] = this
    letreslut = context[key](... ags)delete context[key]
    return reslut
}
Copy the code