日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

记录call、apply、bind的源码

發布時間:2025/5/22 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 记录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的源码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。