记录call、apply、bind的源码
記錄一下call、apply、bind的源碼,然后從根本上明白其用法。
都知道call、apply與bind的用法,call(this,...arguments)、apply(this,[arguments])、var fn = bind(this, ...arguments);fn(...newarguments);
call和apply都是立即執(zhí)行,只是傳參數(shù)形式不一樣,call參數(shù)一字排開,apply參數(shù)是數(shù)組,bind綁定之后返回一個(gè)新函數(shù)但是并不立即執(zhí)行,需要額外調(diào)用的時(shí)候才執(zhí)行,并且,綁定的時(shí)候可以額外傳參數(shù),執(zhí)行的時(shí)候也可以額外傳參數(shù)。
call和apply執(zhí)行的本質(zhì)是,往要綁定的context對(duì)象下添加該函數(shù),然后執(zhí)行,最后將屬性刪除。當(dāng)context值為null,或者undefined時(shí),非嚴(yán)格模式下,它將替換為window或者global全局變量。
Function.prototype.call = function (context) {var context = context || window;context.fn = this;var args = [];for(var i = 1, len = arguments.length; i < len; i++) {args.push('arguments[' + i + ']');}var result = eval('context.fn(' + args +')');delete context.fnreturn result; }?
Function.prototype.apply = function (context, arr) {var context = Object(context) || window;context.fn = this;var result;if (!arr) {result = context.fn();}else {var args = [];for (var i = 0, len = arr.length; i < len; i++) {args.push('arr[' + i + ']');}result = eval('context.fn(' + args + ')')}delete context.fnreturn result; }bind因?yàn)椴粫?huì)立刻執(zhí)行,而是返回一個(gè)函數(shù),一般情況下,該函數(shù)執(zhí)行時(shí)的this指向綁定的對(duì)象。而麻煩的是JS中該函數(shù)還可以通過new來實(shí)例化,而實(shí)例化之后的this要指向新創(chuàng)建的對(duì)象,不能再跟著綁定的對(duì)象走了,所以該函數(shù)內(nèi)部對(duì)this進(jìn)行了額外處理,看它是否是通過new創(chuàng)建的實(shí)例,如果是通過new創(chuàng)建的實(shí)例,this對(duì)象指向新創(chuàng)建的new對(duì)象實(shí)例。
if (!Function.prototype.bind) {Function.prototype.bind = function (oThis) {if (typeof this !== "function") {throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");}var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {},fBound = function () {return fToBind.apply(this instanceof fNOP? this: oThis || this,aArgs.concat(Array.prototype.slice.call(arguments)));};fNOP.prototype = this.prototype;fBound.prototype = new fNOP();return fBound;}; }?
轉(zhuǎn)載于:https://www.cnblogs.com/liujiekun/p/11295183.html
總結(jié)
以上是生活随笔為你收集整理的记录call、apply、bind的源码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bobo老师机器学习笔记1.1 - 什么
- 下一篇: mysql -- 学习记录