免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
bind,call,apply模擬實(shí)現(xiàn)

首先,三者第一個參數(shù)都為this指向

區(qū)別

bind返回的是一個函數(shù)體

call和apply會直接執(zhí)行,但是call參數(shù)需要一個一個進(jìn)行傳遞,apply的第二個參數(shù)是一個數(shù)組

實(shí)現(xiàn)

bind

簡單實(shí)現(xiàn)

Function.prototype.myBind = function(context){  self = this;  //保存this,即調(diào)用bind方法的目標(biāo)函數(shù)  return function(){      return self.applay(context, [...arguments]);  };};

考慮到函數(shù)柯里化的實(shí)現(xiàn)

Function.prototype.myBind = function(context){  // 使用閉包存下初始參數(shù)  var args = Array.prototype.slice.call(arguments, 1),  self = this;  return function() {        // 再次調(diào)用時      var innerArgs = Array.prototype.slice.call(arguments);      var finalArgs = args.concat(innerArgs);      return self.apply(context,finalArgs);  };};

考慮構(gòu)造函數(shù)的實(shí)現(xiàn)

Function.prototype.myBind = function(context){  // 判斷是否為函數(shù)  if(typeof this !== 'function') {    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');  }  var args = Array.prototype.slice(arguments, 1);  self = this;  bound = function() {      var innerArgs = Array.prototype.slice.call(arguments);      var finalArgs = args.concat(innerArgs);      // 判斷this,如果是,則傳遞this即實(shí)例化的對象。      return self.apply((this instanceof F ? this : context), finalArgs);  };  // 處理原型鏈  let F = function(){};  F.prototype = self.prototype;  bound.prototype = new F();  retrun bound;};

call

思路

// 要實(shí)現(xiàn)這個效果var foo ={  value:1}function bar(){  console.log(this.value)}bar.call(foo);//1// 相當(dāng)于做如下事情var foo = {    value: 1,    bar: function() {        console.log(this.value)    }};foo.bar(); // 1

實(shí)現(xiàn)

Function.Prototype.myCall = function(context) {  // this 參數(shù)可以傳 null,當(dāng)為 null 的時候,視為指向 window  var context = context || window;    context.fn = this;  // 對參數(shù)進(jìn)行處理    var args = [];  for(var i = 1, len = arguments.length; i < len; i++) {      args.push(arguments[i]);  }  let result = arguments.length>0 ? context.fn(...args) : context.fn();  delete context.fn;  return result;}

apply

Function.Prototype.myApply = function(context, arr) {  // this 參數(shù)可以傳 null,當(dāng)為 null 的時候,視為指向 window  var context = context || window;    context.fn = this;  let result = arr.length>0 ? context.fn(...arr) : context.fn();  delete context.fn;  return result;}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
前端整理——javaScript部分
(譯) 一篇非常不錯的前端面試文章
js再論call和apply
理解JavaScript Call()函數(shù)原理。
javascript的動態(tài)this與動態(tài)綁定
理解 javascript 里的 bind() 函數(shù) – WEB駭客
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服