js - api - bind analog implementation

js - api - bind analog implementation


  • Micro-channel scan code number of public attention: the front end of the front end of a large front-end , the pursuit of more refined reading experience, together to learn ah
  • After Follow Send key information , free access to a complete set of front-end systems and learning materials old boy python courses
    Here Insert Picture Description

desc

An introductory call on the realization / apply, where talk about analog bind, in fact, bind role and call / apply similar, you can change this point, the difference is that after the implementation of the return of a bind function, and does not own call
on mdn explains: bind () method creates a new function () is called, that this new function is bind the first parameter specifies the bind, the rest of the parameters will be invoked as an argument for the new function use.

var stu = {
  name:"tom",
  age: 18,
};

function say() {
  console.log(`my name is ${this.name},${this.age} years old`);
}

var bindSay=say.bind(stu); 
bindSay();// my name is tom,18 years old

Here Insert Picture Description

code

/**
 * * 改变this指向
 * * 返回一个函数
 * * 可传参
 * * 柯里化
 */


Function.prototype.bind = function (context, ...args) {

  if (typeof this !== "function") {
    throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
  }

  let self = this
  let MiddleFn = function () { }
  let BindFn = function (...rest) {
    return self.apply(this instanceof BindFn ? this : context, args.concat(rest));
  }

  MiddleFn.prototype = this.prototype
  BindFn.prototype = new MiddleFn()
  return BindFn;
}


Published 396 original articles · won praise 786 · views 160 000 +

Guess you like

Origin blog.csdn.net/qq_42813491/article/details/103080260