记录call、apply、bind的源码
記錄一下call、apply、bind的源碼,然后從根本上明白其用法。
都知道call、apply與bind的用法,call(this,...arguments)、apply(this,[arguments])、var fn = bind(this, ...arguments);fn(...newarguments);
call和apply都是立即執行,只是傳參數形式不一樣,call參數一字排開,apply參數是數組,bind綁定之后返回一個新函數但是并不立即執行,需要額外調用的時候才執行,并且,綁定的時候可以額外傳參數,執行的時候也可以額外傳參數。
call和apply執行的本質是,往要綁定的context對象下添加該函數,然后執行,最后將屬性刪除。當context值為null,或者undefined時,非嚴格模式下,它將替換為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因為不會立刻執行,而是返回一個函數,一般情況下,該函數執行時的this指向綁定的對象。而麻煩的是JS中該函數還可以通過new來實例化,而實例化之后的this要指向新創建的對象,不能再跟著綁定的對象走了,所以該函數內部對this進行了額外處理,看它是否是通過new創建的實例,如果是通過new創建的實例,this對象指向新創建的new對象實例。
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;}; }?
轉載于:https://www.cnblogs.com/liujiekun/p/11295183.html
總結
以上是生活随笔為你收集整理的记录call、apply、bind的源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bobo老师机器学习笔记1.1 - 什么
- 下一篇: mysql -- 学习记录