1. 程式人生 > 實用技巧 >改變this指向的方法?call,apply,bind三者區別?自己實現三個方法?

改變this指向的方法?call,apply,bind三者區別?自己實現三個方法?

call,apply,bind為改變this指向的方法

共同點:

  第一個引數都為改變this的指標,若第一個引數為null或者undifined,則this指向預設window

區別:

  call:第二個引數開始都是實參,使用該方法自動執行函式

  apply:第二個引數是一個數組格式的引數列表,使用該方法自動執行函式

  bind:第二個引數開始都是實參,該方法使用後返回一個函式,需要自己呼叫執行

實現call方法:

Function.prototype.myCall = function (context) {
  if(context == null){
    context 
= window; } context.fn = this; const arg = [...arguments].slice(1); const result = context.fn(...arg); delete context.fn; return result; }

實現apply方法:

Function.prototype.myApply = function (context, arr) {
  if(context == null) {
    context = window;
  }
  context.fn = this;
  let result;
  
if(arr == null){ result = context.fn(); }else { result = context.fn(...arr); } delete context.fn; return result; }

實現bind方法:

Function.prototype.myBind = function (context) {
  if(context == null){
    context = window;
  }
  const arg = [...arguments].slice(1);
  const _this = this
; return function Fn() { if(this instanceof Fn) { return _this.call(this, ...arg); } return _this.call(context, ...arg); } }