Javascript動手實現(xiàn)call,bind,apply的代碼詳解
1.檢查當(dāng)前調(diào)用的是否為函數(shù)
2.如果當(dāng)前沒有傳入指向的this,則賦值為window
3.將fn指向當(dāng)前調(diào)用的函數(shù)
4.獲取傳入的參數(shù)
5.將參數(shù)傳入fn進(jìn)行調(diào)用
6.將對象上的fn刪除
7.返回結(jié)果
//普通call的實現(xiàn) function hello(){ console.log('hello 我是'+this.name); }; let person = { name:'krys' }; var name = 'liang';//只有var的變量屬于window hello();// 'hello 我是liang' hello.call(person);//'hello 我是krys' hello.call();//'hello 我是liang' let person2 = { name:'lwl' } Function.prototype.mycall = function(context){ //不傳入?yún)?shù)的時候,默認(rèn)為window if(typeof this !== "function"){ throw new TypeError('Error'); } context = context || window; context.fn = this;//fn就是上面的hello方法 const args = [...arguments].slice(1);//第一個參數(shù)不要 const result = context.fn(...args);//把剩下的其他參數(shù)傳給hello delete context.fn; return result; } hello.mycall(person2);
function getParams(){ console.log('我是',this.name,'獲取一些參數(shù)',...arguments); } let person3 = { name:'hhh' }; getParams.apply(person3,['hello','world']) Function.prototype.myApply = function(context){ if(typeof this !== "function"){ throw new TypeError() } context = context || window; context.fn = this; let result; if(arguments[1]){ //如果有傳入?yún)?shù)數(shù)組 console.log(arguments[1]) result = context.fn(...arguments[1]); }else{ result = context.fn(); } delete context.fn; return result; } getParams.myApply({name:'llll'},['jjj','kkkk','llll']);
function getParams(){ console.log('我是',this.name,'獲取一些參數(shù)',...arguments); } let person3 = { name:'hhh' }; let person4 = { name:'tttt' }; getParams.bind(person3,'hello','world') getParams.bind(person4,'hello','world')('jjj','kkk'); Function.prototype.myBind = function(context){ if(typeof this !== "function"){ throw new TypeError() } context = context || window; const _that = this; const args = [...arguments].slice(1); return function F(){ if(this instanceof F){ return new _that(...args,...arguments);//這里的arguments是上面的jjj kkk } return _that.apply(context,args.concat(...arguments));//這里的arguments是上面的jjj kkk } } getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
uni-app小程序?qū)崿F(xiàn)微信在線聊天功能(私聊/群聊)
這篇文章主要介紹了uni-app小程序?qū)崿F(xiàn)微信在線聊天(私聊/群聊),今天記錄一下項目核心功能的實現(xiàn)過程。頁面UI以及功能邏輯全部來源于微信,即時聊天業(yè)務(wù)的實現(xiàn)使用socket.io,前端使用uni-app開發(fā),后端服務(wù)器基于node實現(xiàn),數(shù)據(jù)庫選擇mongoDB,需要的朋友可以參考下2023-02-02es6 for循環(huán)中l(wèi)et和var區(qū)別詳解
這篇文章主要介紹了es6 for循環(huán)中l(wèi)et和var區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01stream.js 一個很小、完全獨立的Javascript類庫
stream.js 是一個很小、完全獨立的Javascript類庫,它為你提供了一個新的Javascript數(shù)據(jù)結(jié)構(gòu):streams2011-10-10javascript動態(tài)添加表格數(shù)據(jù)行(ASP后臺數(shù)據(jù)庫保存例子)
本文,我將以一個類似的例子來做一個前臺用Javascript動態(tài)添加數(shù)據(jù)項,后臺保存到數(shù)據(jù)庫的例子。2010-05-05